Home

mikroBasic PRO for AVR User Manual v100

image

Contents

1. 27 Help Menu Options 28 Keyboard Shortcuts 29 IDE OVervIGW ore x 31 Customizing IDE Layout 32 Docking Windows 2 22 22 2 32 Saving Layout wade da x CY CR Rep 33 you Nave a via eee ERA 33 Auto E Aud bead deed vedas 34 Advanced Code 35 Advanced Editor Features 35 Code 36 Code Folding ilu la 37 Parameter Assistant 38 Code Templates Auto Complete 38 Auto Correct ccs us enam fede RETRO ER ae ER URL RR 38 Spell Checker Pa Ter exe dein 39 Bookmarks 39 ICM PPP 39 Comment 39 Code Explorer ue UE ues EUER ER Uer RUP Re ORE 40 Routine ec i eR OE RR pe e ue ee eR 41 Project Manager 42 Project Settings Window
2. 396 SPI Rectangle 397 Gled BOX secta us pide Ren abs ER FER 398 SPI Gled Circle 2 x RR Rn ICE Ae RAE Deas 398 XX MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Table of Contents Glod Set Font a ee ee NAAR 399 _ Write 400 SPI Write 401 Image esses RR ame ARS eh ad 402 Library 1 402 The example demonstrates how to 402 HW Connection 405 SPl Eed Library ioc n ERR XA VERE GU NEG 406 External dependencies of SPI Lcd Library 406 Library ROUUNGS eee aped ati e ead 406 SPI Led Config sog cer e e e eh eden e RR RR 407 SPI LOT OUE or 408 Lod Oul 24 Dec DR bad pedddudea t 408 SP O Fn Bee eo o qoe Rb 409 SPI Led Chr Cp zia ECRIRE SEES ERES 409 SPI bed Cm eite ate a atte 410 Available SPI Lcd Commands 410 Library Example ies erem doc o Red 411 HW Connection csv ee RR RE
3. 376 Spi Ethernet putString 376 Spi Ethernet putConstString 377 Spi Ethernet getByte 377 Spi Ethernet getBytes 378 Spi Ethernet UserTCP 379 Spi Ethernet 380 Library Example 2 niim ene awe ened wed eda 381 This code 381 HW Connection 25545 bee due A E ea any 389 SPI Graphic Lcd Library 390 External dependencies of SPI Graphic Lcd Library 390 Library Routines 390 SPI GledzInit omes men Bets Retro Rer oe ee Ed Sx eee 391 SPI Set 5 392 SPI Set Page 392 SPI Gled Set X casis ee ERE XT EAR EE RR ENS UE RA 393 SPI_Glcd_Read_Data 393 SPI Gled Write Data 394 SPISGledg UR SER 394 SPI Gled Dot aiu ex ERE RR EE ER SERERE d RA 395 SPI Glcd Line 20 bac ie a eee eee dos e ea 395 Gled V LING assis cca ex eR Ree eR oe eR RE 396 SPI Gled H Line
4. 153 Select Case Statement 154 Nested Case Statements 155 Iteration Statements 155 For Statement zug ez aes et DO Iberia iu peat a eee ah eae 156 Endless Loop xii cada ox E ERE a a ae 156 While Stateimient oed sme eae ro RU Re 157 Do Statement eren S268 DRE eth oe cide aS 158 Jump Statements 158 Break and Continue Statements 159 Break Statement 159 Continue Statement i asite rema maire 159 Exit Statement suc ccc eens ape A E ROUES RT RR 160 Goto Statement sae hale Wwe eh eae EE 161 Gosub Statement sd rsrsr serais dad 162 asm Statement 522252 e iuis eee 163 Directives DX GINA V DIS PEU IER Ea DU 164 Compiler Directives 164 Directives ZDEFINE and ZUNDEFINE 164 Directives IFDEF ELSEIF and ZELSE 164 Predefined Flags 54g E ye bas ele bebe ae EAT Qin 165 Linker Directives oes dg Had eee RR 166 Directi
5. Res ERR ER ORA wens RUNE ER 133 X MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Table of Contents Function 133 Example site aed ean 133 RT 134 Forward declaration 135 cs 136 Type Categories heed eka Rh ade 136 Simple Types 137 AIVAYS ie sed She pea ped 138 Array Declaration 138 Constant Arrays 138 SUINGS ane CMT 139 Nou 139 POlDters io MICE MER beens 140 Operator wees rr ee e eee 140 SIMUCTUNES ss ons xav ORE EAE REN RR Rees RR ERR TI M d Ie 141 Structure Member Access 142 Types Conversions 143 Implicit Conversion 143 Promotion 5 ae REA IE Y ERAN A on 143 aestum OE Rue 144 Explicit Conversion 144
6. UR ER 145 Operators Precedence and 145 Arithmetic Operators 146 Division Zero secc redai orra eim p uses ace 146 Unary Arithmetic Operators 146 Relational Operators 147 Relational Operators in Expressions 147 Bitwise Operators 148 Bitwise Operators Overview 148 Logical Operations on Bit 148 The bitwise operators and or and xor perform logical oper 148 Unsigned and Conversions 149 Signed and Conversions 149 Bitwise Shift Operators 150 Boolean Operators 150 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XI Table of Contents mikroBasic PRO for AVR Lo ce ER E eee CR ERN ee KORR RC RC I RD RU e ROT a 151 Statements orari 152 Assignment Statements 152 Conditional Statements 153 lf Statement scie 2 sss wm Rem d ax mx AR 153 Nested if statements
7. 341 Soft 2 Sips tk Rae x aen 341 Soft I2C 342 Library Example ade tate 343 Software SPI Library 1 346 External dependencies of Software SPI Library 346 Library RoutineS ERR pu 347 Soft SP Init oe e RR ae CRT ed 347 Soft SPI Read 2 2 e ER ee iere 348 Soft SPI ex or Re or RR 348 Library 349 Software UART Library 351 External dependencies of Software UART Library 351 Library ca carie Ra poe e UR aT 351 SOR UART Init RP EP eda 352 Soft Read eere RR p ARR RACER 353 Soft UART Write seedee e RR che ee 354 Soft UART 355 Library EXAMP 202452 cree eed aed ed 356 Sound Library 2 20402 Ree Rr mere dee eae 357 External dependencies of Sound Library 357 Library Routines 357 Sound INI 4 cua CE
8. 182 CANSPI OP MODE eh de eben 182 CANSPI_CONFIG_FLAGS 182 CANSPI_TX_MSG_ 183 CANSPI RX MSG FLAGS 184 GANSPI MASK anno EROR TOO RA PR RE 184 FIETER ue Dear CORR ee eed 184 Library 185 HW Connection 188 Compact Flash 189 External dependencies of Compact Flash Library 190 Library Routines 191 CT Init xe edere e a 192 CE Detect xv s Re veg de agde S a o 193 GT Enable eges Ye RR awh ER ERAS C 193 CT Disable OR ed RO UR VO ERE Tues 193 CT Read Init caer Chart ex RGus one oe 194 Cf Read Byte 194 Gf Write Init RR 195 Cf Write Byte 195 Cf Read Sector 196 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XIII Table of Contents mikroBasic PRO for AVR Cf Write Sector 196 CT F
9. SPI Lcd8 Config 0 Entialrze in 8bit mode via SPI SPI Lcd8 Cmd LCD CLEAR Clear display SPI Lcd8 Cmd LCD CURSOR OFF Turn Cursor Off SPI Lede Out 1 6 text Print text to Led lst row 6th column SEI Lede Chr Cer Append SPI 8 Out 2 1 mikroelektronika Print text to Led 2nd Ist columh SPI Led Out 3 l1 text For Lcd modules with more than two rows SPI Leds Out 4 15 text For Lcd modules with more than two rows end 418 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection 9LVOANLV SPI Lcd8 HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 419 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI T6963C GRAPHIC LCD LIBRARY The mikroBasic PRO for AVR provides a library for working with Glcds based TOSHIBA T6963C controller via SPI interface The Toshiba T6963C is a very popu lar Lcd controller for the use in small graphics modules It is capable of controlling displays with a resolution up to 240x128 Because of its low power and small out line it is most suitable for mobile applications such as PDAs MP3 players or mobile measurement equipment Although this controller is small it has a capability of dis playing and merging text and graphics and it manages all interfacing signals to the displays Row and Column
10. 43 Library Manager xe eke 44 Error WIDdOW 555559 xs RS Ea eR E 46 Statistics 235 ete eve ern qu tn RU dU AUR ae aie cee ar tei 47 Memory Usage Windows 47 RAM 47 Rx Memory Space 47 Data Memory Space 48 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD V Table of Contents mikroBasic PRO for AVR Special Function Registers 48 Summarizes all Special Funct 48 General Purpose Registers 49 ROM Memory 49 ROM Memory 49 ROM Memory Allocation 50 Procedures 50 Procedures Size Window 50 Procedures Locations Window 51 ATME WindOW see cbe ree cR Ee UR 51 Integrated Tools 1i crede eee lan a 52 USART Terminal uu etr Ree ee eae ee be 52 Chart 3 5 Gest db UC SUE Re ERA 53 adest rdc
11. 89 Accessing Individual Bits 90 Accessing Individual Bits Of Variables 90 SDIETyDO su secius pa aa eA eel eda eel al 90 D ODO PL 91 InterruptS ia eed beh eee bad 92 Function Calls from 92 Linker Directives 2 5 iu AERE GG XE 94 Directive absolute 94 Directive Org ipee qeesrdvbemnrivtesrsrbeeiecbesqeex 94 Built in 95 bOr aeta pu 96 LET 96 PINGE cope atest te Seon ane ee eae DC 96 Highest sci Seed eae ace Poe 97 Doa pp REMIT 97 DOC casui 97 Delay 8 222 98 Delay ms 98 Mdelay ims ee ae dg tera cales Had RD alee REA 98 Delay da epee 99 CIOCK WAZ aoa xe eus eR Ree UR arp URN 99 Clock MHZ 525v RR E eta ee E ERU AE 99 SetFuncCall 25 54 eee Re eH S RO EE 100 Code Optimization
12. const CANSPI MODE BITS as byte SEO Use this to access opmode bits CANSPI MODE NORMAL as byte 0 CANSPI MODE SLEEP as byte 20 CANSPI MODE LOOP as byte 40 CANSPI MODE LISTEN as byte 60 CANSPI MODE CONFIG as byte 80 CANSPI CONFIG FLAGS The CANSPI CONFIG FLAGS constants define flags related to the CANSPI mod ule configuration The functions CANSPIInitialize CANSPISetBaudRate CANSPISetMask and CANSPISetFilter expect one of these or a bitwise combina tion as their argument const CANSPI CONFIG DEFAULT as byte SFF CANSPI CONFIG PHSEG2 PRG BIT as byte 501 CANSPI CONFIG PHSEG2 PRG ON as byte SFF XXXXXXX1 CANSPI CONFIG PHSEG2 PRG OFF as byte XXXXXXX0 CANSPI CONFIG LINE FILTER BIT as byte 02 CANSPI CONFIG LINE FILTER ON as byte SFF XXXXXX1X CANSPI CONFIG LINE FILTER OFF as byte SFD XXXXXXOX CANSPI CONFIG SAMPLE BIT as byte 04 CANSPI CONFIG SAMPLE ONCE as byte SFF XXXXX1XX CANSPI CONFIG SAMPLE THRICE as byte SFB XXXXX0XX CANSPI CONFIG MSG TYPE BIT as byte 08 CANSPI CONFIG STD MSG as byte SFF XXXX1XXX CANSPI CONFIG XTD MSG as byte 5 7 XXXXOXXX 182 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries CANSPI CONFIG DBL BUFFER
13. dee RR 412 SPI 8 bit interface 413 External dependencies of SPI Lcd Library 413 Library RoutineS 413 SPI Lode Conflg esa cerar ee ee RET 414 SPI Lod8 Qut 2222514 i034 Gadhia eed haa bade oceans 415 Cp i wea Lore oe eere e eee 415 Lode Chr 54s e ER Eb 416 Chr Opa cid aet ew ue x 416 SPI Led RE 417 Available SPI Lcd8 Commands 417 Library Example suse uda RR ERRARE 418 HW Connection 419 SPI T6963C Graphic Lcd 420 External dependencies of SPI T6963C Graphic Lcd Library 420 Library Routines 421 SPI T6963C Config 422 SPI T6963C WriteData 423 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XXI Table of Contents mikroBasic PRO for AVR SPI T6963C WriteCommand 424 SPI T6963C SetPtr 2 2 duse Rd 424 SPI 6963 424 6963 oti eanan E
14. CANSPI CONFIG MATCH MSG TYPE see CANSPI constants The CANSPI module must be in Config mode otherwise the sub function will be ignored See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page set the appropriate filter value and message type CANSPISetOperationMode CANSPI MODE set CONFIGURATION mode CANSPI module must be in config mode for filter settings Set ad of filter Bl Fi to 3 CANSPISetFilter CANSPI FILTER Bl F1 3 CANSPI CONFIG XTD MSG 179 CHAPTER 6 Libraries mikroBasic PRO for AVR CANSPIRead Description sub function CANSPIRead dim byref id as longint dim byref rd data as byte 8 dim data len as byte dim CAN RX MSG FLAGS as byte as byte 0 if nothing is received oxFF if one of the Receive Buffers is full message received If at least one full Receive Buffer is found it will be processed in the following way Message ID is retrieved and stored to location provided by the id parameter Message data is retrieved and stored to a buffer provided by the data parameter Message length is retrieved and stored to location provided by the data_ len parameter Message flags are retrieved and stored to location provided by the CAN RX MSG FLAGS para
15. FF FF FF FF FF FF FF FF FF FF FF FF FF FF PERYVEYEPVYYYYYY DEN FF FF FF FF FF FF FF FF FF FF FF YHHEYSYYVYYYYYY DITE FF FF FF FF FF FF FF FF FF FF FF FF FF FF yy TEE FF FF FF FF FF FF FF FF FF FF FF FF FF FF IN FF FF FF OFF FF FF FF FF FF FF FF FF FF FF FF FF DITE FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF DTE FF FF FF FF FF FF FF E EEPROM Edit Input Format Edit Value Dec EEPROM Address Hex No Ox Edit Hex Start Address Ox FFFF Size Float v AutoInc Byte Word DWord String 54 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment 7 Segment Display Decoder The 7 Segment Display Decoder is a convenient visual panel which returns deci mal hex value for any viable combination you would like to display on 7seg Click on the parts of 7 segment image to get the requested value in the edit boxes You can launch it from the drop down menu Tools 7 Segment Decoder or by clicking the Seven Segment Icon Tools toolbar Common cathode 0x71 PI Common anode MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
16. For more information on creating new libraries see Creating New Library Dutput Settings Output Settings V Generate ASM file V Include HEX opcodes Include ROM constants Include ROM Addresses Generate list file Include debug info Include source lines output files Optimization level Compiler Case sensitive V Dynamic link For string literals Build all files as library MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 61 CHAPTER 2 Environment mikroBasic PRO for AVR REGULAR EXPRESSIONS Introduction Regular Expressions are a widely used method of specifying patterns of text to search for Special metacharacters allow you to specify for instance that a particu lar string you are looking for occurs at the beginning or end of a line or contains n recurrences of a certain character Simple matches Any single character matches itself unless it is a metacharacter with a special meaning described below A series of characters matches that series of characters in the target string so the pattern short would match short in the target string You can cause characters that normally function as metacharacters or escape sequences to be interpreted by preceding them with a backslash For instance metacharacter matches beginning of string but matches character and matches etc Examples unsigned match
17. Available Lcd Commands Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected LCD RETURN HOME Lj T LE Shift display left without changing display data RAM D Shift display right without changing display data RAM 244 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Library Example The following code demonstrates usage of the Lcd Library routines LCD module connections dim LCD RS as sbit at PORTD dim LCD EN as sbit at PORTD dim LCD D4 as sbit at PORTD dim LCD D5 as sbit at PORTD dim LCD D6 as sbit at PORTD dim LCD D7 as sbit at PORTD dim LCD RS Direction as sbit dim LCD EN Direction as sbit dim LCD D4 Direction as sbit dim LCD D5 Direction as sbit dim LCD D6 Direction as sbit dim LCD D7 Direction as sbit End Lcd module connections dim txtl as char 17 T txt2 as char 1 txt3 as 9 txt4 as char 8 1 as byte sub procedure Move Delay Delay ms 500 OF Go at at at at at at DDRD DDRD DDRD DDRD DDRD DDRD B2 B3 B4 B5 B6 B7 Loop variable CHAPTER 6 Libraries Function used for text moving You can change the moving speed here end sub main txtl mikroElektronika txt2 EasyAVR5A Ext Loddbrt txt4 example Ged 9 LCD Duti l o tx
18. 0 as pin 1 as input input Set Set PORTC PORTC pin 2 3 input input initial value for current duty initial value for current duty Set PORTB pin 1 as output pin Set PORTE pin 2 as output pin to datasheet PWM16 PRESCALER 16bit 1 PWM16 INVERTED 255 1 while TRUE PING lt gt 0 Delay ms 40 Inc current duty PWM Set Duty current duty end if 1E PING Bi lt gt 0 Delay_ms 40 Dec current duty PWM Set Duty current duty end if if PINC B2 lt gt 0 Delay ms 40 inc current dutyl PWM1 Set Duty current dutyl if PING Bs gt Delay ms 40 Dec current dutyl PWM1 Set Duty current dutyl i end if wend MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD then then then then Endless loop Detect if PORTC pin 0 is pressed Small delay to avoid deboucing effect Increment duty ratio Set incremented duty Detect if PORTC pin 1 is pressed Small delay to avoid deboucing effect Decrement duty ratio Set decremented duty ratio Detect if PORTC pin 2 is pressed Small delay to avoid deboucing effect Increment duty ratio Set incremented duty Detect if PORTC pin 3 is pressed Small delay to avoid deboucing effect Decrement duty ratio Set decremented duty ratio 323 CHAPTER 6 Libraries mikroBasic PRO f
19. Ps2 Config Ps2 Key Read 302 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Ps2 Config Prototype Initializes the MCU for work with the PS 2 keyboard Global variables PS2 Data Data signal line PS2 In Clock Clock signal line in PS2 Out Clock Clock signal line out PS2 Data Direction Direction of the Data pin PS2 Clock Direction Direction of the Clock pin must be defined before using this function PS2 pinout definition dim PS2 Data as sbit at PINC BO dim PS2 In Clock as sbit at dim PS2 Out Clock as sbit at 1 dim 52 Data Direction as sbit at DDRC BO dim PS2 Clock Direction sbit at DDRC B1 End of PS2 pinout definition Ps2 Config Init PS 2 Keyboard MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 303 CHAPTER 6 Libraries mikroBasic PRO for AVR Ps2 Key Read sub function Ps2 Key Read dim byref value as byte dim byref spe cial as byte dim byref pressed as byte as byte 1 if reading of a key from the keyboard was successful 0 if no key was pressed The function retrieves information on key pressed Prototype Parameters value holds the value of the key pressed For characters numerals punctu Description ation marks and space value will store the appropriate ASCII code Routine recognizes the function of Shift and Caps Lock and be
20. SPI T6963C circle 120 64 10 SPI T6963C WHITE SPI T6963C circle 120 64 30 SPI T6963C WHITE SPI 169530 cirole 120 64 50 SPI T6963C WHITE SPI T6963C circle 120 64 70 SPI T6963C WHITE SPI T6963C circle 120 64 90 SPI T6963C WHITE SPI T6963C ecircle 120 54 110 SPI 5963 WHITE SPI T6963C clrole 120 64 130 SPI T6963C WHITE SPI T6963C sprite 76 4 Geunste rn 88 11 Draw a Sprite SPI T6963C se torPanel l Select other graphic panel SPI T6963C image 8mikroe Fill the graphic screen with a picture while TRUE Endless loop If PORTA 0 is pressed toggle the display between graphic panel 0 and graphic 1 if bit 0 then Inc panel panel panel and 1 SPI T6963C setPtr SPI T6963C grMemSize i SPI T6963C txtMemSize panel SPI T6963C GRAPHIC HOME ADDRESS SET MIKROELEKTRONIKA Delay ms 300 If PORTA 1 is pressed display only graphic panel else if 1 bit 0 then SPI T6963C graphics l SPI T6963C text 0 Delay ms 300 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 439 CHAPTER 6 Libraries mikroBasic PRO for AVR If PORTA 3 is pressed 1 if PINA3 bit SPI 7 SPI 1 Delay ms 300 0 If PORTA 4 is pressed 1 if PINA4 bit Tne curs if curs Curs end if select case case 0 Y 0 3 display text and graphic pan
21. e rue ud Rl MU DM 466 EWI PEE 467 TAI Status cach iR eei RR Ce Sa a 467 TWIECI SO gu RELAX eh eae DR 467 Library 467 This code demonstrates use of TWI Library proc 467 HW Gonnectiom axe dee Eher QR eee 468 Library ssepe E RENE BA Ea TE RERO EE 469 Library Routines 469 B sdpAM aep M TE 470 UARTx Init Advanced 471 UARTx_Data_Ready 472 UARTx Read leen lx mele dac cx ceri behav 472 UARTx Read Text 473 VARTA E E ote 474 UARTx Write Text 474 Library Example 22 nodi dweeb ended 475 HW 475 Button Library dide exe RE ER ae aad Seb Ei 476 External dependencies of Button Library 476 Library Routines 476 476 Conversions 4 478 Library Routin S 2 22 478 Byte TOSI 252224 eae 478 ohortl
22. Select DAC chip Store valueDAC 11 8 to see MCP4921 datasheet Send high byte via SPI 0 SPI to temp 7 0 Deselect DAC chip Endless loop If PAO button is increment value Chip select 1 end sub main InitMain Perform main initialization value 2048 When program starts DAC gives the output the mid range while TRUE if PINAO bit and value lt 4095 then pressed Inc value d else MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 365 CHAPTER 6 Libraries mikroBasic PRO for AVR if 1 bit and value gt 0 then If PAL button is pressed Dec value d decrement value end if end if DAC Output value Send value to DAC chip Delay ms 1 Slow down key repeat pace wend end HW Connection All lines are disconnected Vref line is connected Vcc line is connected J10 R12 1K DAC CONNECTOR VEC OSCILLATOR 9LVOAWLV SPI HW connection 366 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR SPI ETHERNET LIBRARY CHAPTER 6 Libraries The 282760 is a stand alone Ethernet controller with an industry standard Serial Peripheral Interface SPI It is designed to serve as an Ethernet network interface for any controller equipped with SPI The enc28760 meets all of the IEEE 802 3 specifications It incorporates a number of packe
23. rst Direction Direction of Reset signal pin must be defined before using this function 445 CHAPTER 6 Libraries mikroBasic PRO for AVR T6963C module connections dim T6963C ctrlPort as byte at PORTC dim T6963C dataPort as byte at PORTD dim T6963C ctrlPort Direction as byte at DDRD dim 6963 dataPort Direction as byte at DDRC dim T6963C ctrlwr as sbit at PORTC B2 dim T6963C ctrlrd as sbit at 1 dim T6963C ctrlcd as sbit at PORTC BO0 dim T6963C ctrlrst as sbit at PORTC B4 dim T6963C ctrlwr Direction as sbit at DDRC B2 dim T6963C ctrird Direction as sbit at DDRC B1 dim 6963 ctrlcd Direction as sbit at DDRC BO dim T6963C ctrlrst Direction as sbit at DDRC B4 End of T6963C module connections init display for 240 pixel width 128 pixel height and 8 bits character width T6963C init 240 128 8 T6963C WriteData Prototype sub procedure 6963 WriteData dim mydata as byte Writes data to T6963C controller Description Parameters mydata data to be written Toshiba Glcd module needs to be initialized See the T6963C Init routine 446 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries T6963C WriteCommand Prototype sub procedure 6963 WriteCommand dim mydata as byte Writes command to T6963C controller Description Parameters mydata command to be written Toshiba Glcd mod
24. 11 0 456 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries T6963C Cursor Height Prototype sub procedure T6963C Cursor Height dim n as byte Set cursor size Description Parameters n cursor height Valid values 0 7 Toshiba Glcd module needs to be initialized See the T6963C Init routine Eme T6963C Graphics Prototype sub procedure 6963 Graphics dim n as byte Enable disable graphic displaying Description Parameters n on off parameter Valid values o disable graphic dispaying and 1 enable graphic displaying Toshiba Glcd module needs to be initialized See the 6963 Init routine enable graphic displaying T6963C Graphics l T6963C Text Prototype sub procedure 6963 Text dim n as byte Enable disable text displaying Description Parameters n on off parameter Valid values o disable text dispaying and 1 enable text displaying Toshiba Glcd module needs to be initialized See the T6963C Init routine enable text displaying T6963C Text 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 457 CHAPTER 6 Libraries mikroBasic PRO for AVR T6963C Cursor Prototype sub procedure 6963 Cursor dim n as byte Nothing Set cursor on off Description Parameters n on off parameter Valid values 0 set cursor off and 1 set cursor on T
25. LCD 2X16 4x4 Keypad connection scheme MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 239 CHAPTER 6 Libraries mikroBasic PRO for AVR LCD LIBRARY The mikroBasic PRO for AVR provides a library for communication with Lcds with HD44780 compliant controllers through the 4 bit interface An example of Lcd con nections is given on the schematic at the bottom of this page For creating a set of custom Lcd characters use Lcd Custom Character Tool External dependencies of Lcd Library The following variables must be defined in all projects using Lcd Library dim sfr LCD RS as sbit external dim LCD EN as sbit sfr external dim LCD D7 as sbit sfr external dim LCD D6 as sbit sfr external dim LCD D5 as sbit sfr external dim LCD D4 as sbit sfr external LCD RS Direction Sbit sfr external Direction external dim Direction sbit sfr external LCD sbit LCD as dim as D6 Direction sfr external dim a D5 Direction sfr external 240 S sbit dim LCD D4 Direction f as sbit sfr external Data 4 direction pin Description Register Select line Enable line DA dim LCD D7 as sbit at dim PORTD LCD RS as sbit at B2 LCD EN as sbit at 5 bit at dim LCD PORTD B6 dim LCD Data 6 line dim LCD D6 as sbit at PORTD B5 Data 4 line D4 as sbit at PORTD B7 Register Select direction 451 220
26. mac RAM buffer containing valid MAC address ip RAM buffer containing valid IP address fullDuplex ethernet duplex mode switch Valid values o half duplex mode and 1 full duplex mode Requires The appropriate hardware SPI module must be previously initialized const Spi Ethernet HALFDUPLE const Spi Ethernet FULLDUPLE Description myMacAddr as byte 6 my MAC address my as byte 4 my IP addr 0 00 0x14 0xA5 0 76 0x19 my 0x3F myIpAddr 192 myIpAddr 168 myIpAddr 20 myIpAddr 60 Spi Spi Ethernet Init PORTC 0 PORTC 1 myMacAddr myIpAddr Spi Ethernet FULLDUPLEX 370 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR CHAPTER 6 Spi Ethernet Enable Description sub procedure Spi Ethernet Enable dim enFlt as byte Nothing This is MAC module routine This routine enables appropriate network traffic on the ENC28J60 module by the means of it s receive filters unicast multicast broadcast crc Specific type of network traffic will be enabled if a correspon ding bit of this routine s input parameter is set Therefore more than one type of network traffic can be enabled at the same time For this purpose predefined library constants see the table below can be ORed to form appropriate input value Parameters enF1t network traffic receive filter flags Eac
27. sbit at DDRB Bl End Port Expander module connections main text mikroElektronika If Port Expander Library uses SPI1 module SPIL Insti Initialize SPI module used with PortExpander Spi Rd Ptr SPI1 Read Pass pointer to SPI Read sub function of used SPI module If Port Expander Library uses SPI2 module 8212 Tait Initialize SPI module used with PortExpander Spr Rd Ptr SPI2 Read Pass pointer to SPI Read sub function of used SPI module SPI Led Config 0 Initialize Lcd over SPI interface SPI Lcd Cmd LCD CLEAR Clear display SPI Lcd Cmd LCD CURSOR OFF Turn Cursor off SPI Lcd Out 1 6 mikroE Print text to Led dst row 6th column OPI Led ONE CrCl Append SPI Led Out 2 1 text Print text to Lcd 2nd row lst column end MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 411 CHAPTER 6 Libraries mikroBasic PRO for AVR HW Connection 9LVOAWNLV 8 SPI Lcd HW connection 412 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI LCD8 8 BIT INTERFACE LIBRARY The mikroBasic PRO for AVR provides a library for communication with Lcd with HD44780 compliant controllers in 8 bit mode via SPI interface For creating a custom set of Lcd characters use Lcd Custom Character Tool Note Library uses the SPI module for communication The user must ini
28. Auto Save v Auto Completa Enable Auto Save Timeout Interval 3 4 minutes Highlighter Highlight begin end pairs V Highlight brackets Spelling V Check Spelling Comment style e perp qi single line Advanced Editor Options T Open options dialog Code Folding V Enable code folding Show Ident Guides Tools Output Code Assistant If you type the first few letters of a word and then press Ctrl Space all valid identi fiers matching the letters you have typed will be prompted in a floating panel see the image below Now you can keep typing to narrow the choice or you can select one from the list using the keyboard arrows and Enter sit unsigned char SP variable sfr unsigned char SPDR variable sfr unsigned char SPSR variable sfr unsigned char SPCR variable 36 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Code Folding Code folding is IDE feature which allows users to selectively hide and display sec tions of a source file In this way it is easier to manage large regions of code within one window while still viewing only those subsections of the code that are relevant during a particular editing session While typing the code folding symbols and appear automatically Use the folding symbols to hide unhide the code subsections PORTA 0 Lcd Init LCD Ou
29. Led Che 27 6 hours 20 48 Lcd Chr 2 7 hours mod 10 48 Lcd Chr 2 9 minutes 10 48 t minutes mod 10 48 seconds 10 48 seconds mod 10 48 Lcd Chr 2 12 Lcd Chr 2 13 end sub Les 10 t Performs project wide init sub procedure Init Main Soft I2C Tnit Initialize Soft I2C communication Led Initialize Lcd Lcd Cmd LCD CLEAR Clear Lcd display Lcd Cmd LCD CURSOR OFF Turn cursor oft Led Out l 1 Dater Prepare and output static text on Lcd Led Ome l 9 E Log Che i 11 2 Led Duti 2 1 T7345 7 Led Chrq2 8 1 Log Che epi Tg Led Qut 1 12 200 end sub 344 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR CHAPTER 6 Libraries TSS SSeSS SSeS Sa see Main sub procedure main Init Main while TRUE Read Time Transform Time Display Time wend end Perform initialization Endless loop Read time from RTC 8583 Format date and time Prepare and display on Lcd MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 345 CHAPTER 6 Libraries mikroBasic PRO for AVR SOFTWARE SPI LIBRARY The mikroBasic PRO for AVR provides routines for implementing Software com munication These routines are hardware independent and can be used with any MCU The Software SPI Library provides
30. Software SPI Library Software UART Library Sound Library SPI Library SPI Ethernet Library SPI Graphic Lcd Library SPI Lcd Library SPI Lcd8 Library SPI T6963C Graphic Lcd Library T6963C Graphic Lcd Library TWI Library UART Library Miscellaneous Libraries Button Library Conversions Library Math Library String Library Time Library Trigonometry Library See also Built in Routines 168 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR LIBRARY DEPENDENCIES CHAPTER 6 Libraries Certain libraries use depend on function and or variables constants defined in other libraries Image below shows clear representation about these dependencies For example uses Glcd Fonts and Port Expander library which uses SPI library This means that if you check SPI library in Library manag er all libraries on which it depends will be checked too Related topics Library manager AVR Libraries MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CANSPI jJ se C_Type CF_FAT16 i Compact Flash SPI T6963C Trigonometry T6963C SPI Ethernet SPI Glcd SPI Lcd SPI Lcd8 d Conversions J String Fonts Lcd Led Constants _ MMC FAT16 MMC
31. Toshiba Glcd module needs to be initialized See the T6963C Init routine MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 449 CHAPTER 6 Libraries mikroBasic PRO for AVR T6963C Write Text sub procedure T6963C Write Text dim byref str as byte 10 dim x y mode as byte Nothing Writes text in the current text panel of Glcd at coordinates x y Prototype Parameters str text to be written x text position on x axis y text position on y axis node mode parameter Valid values 6963 ROM MODE OR T6963C ROM MODE XOR T6963C ROM MODE AND and T6963C ROM MODE TEXT Mode parameter explanation Description OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in the negative mode i e white text on black background AND Mode The text and graphic data shown on display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Toshiba Glcd module needs to be initialized See the T6963C Init routine Example T6963C
32. WordToStr year outstr Write Str ouUbkstr ByteToStr month outstr Write Str outstr WordToStr day outstr Write Sbtr outstr WordToStr hour outstr Write WordToStr minute outstr Write Strooubstr get file size fsize Cf Fat Get File Size LongIntToStr fsize outstr Write Str outstr else file was not found signal it UART1 Write 0x55 Delay ms 1000 UART1 Write 0x55 end if end sub Pee em ME Tries to create a swap file whose size will be at least 100 sectors see Help for details sub procedure M Create Swap File dim i as word for i 0 to 511 Buffer i i next i size Cf Fat Get Swap File 5000 mikroE txt 0x20 see help on this sub function for details if size lt gt 0 then 208 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR CHAPTER 6 LongIntToStr size fat txt Write Str fat txt for i 0 to 4999 Cf Write Sector size Buffer size sizetl VARTI Write next i end if end sub Main Uncomment the sub function s to test desired operation s main ing EAT TXT FATI6 not found file contents XX CF FAT16 library by Anton Rieckert file contents 37 10 newline filename MIKROOOxTXT we will use PORTC to signal test end DDRC OxFF PORTC 0 Libraries the UARTI Trmit 19200 Set up USART for file read delay ms 100 V
33. 1 INVE Selects the inverted PWM mode on second PWM library if it exists in Library Manager PHM NON INVERTED INVE Selects the normal non inverted PWM mode _PWM1_PRE eer the normal non inverted PWM mode on sec ond PWM library if it exists in Library Manager 1 NON INVERTE Note Not all of the MCUs have both PWM and PWM1 library included Sometimes like its the case with ATmega8515 MCU has only PWM library Therefore constants that have in their name PWM1 are invalid for ATmega8515 and will not be visible from Code Assistant It is highly advisable to use this feature since it handles all the constants available nad eliminates any chance of typing error MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 309 CHAPTER 6 Libraries mikroBasic PRO for AVR PWM Init Prototvpe sub procedure PWM Init dim wave mode as byte dim prescaler as yp byte dim inverted as byte dim duty as byte Initializes the PWM module Parameter wave_mode is a desired PWM mode There are two modes Phase Correct and Fast PWM Parameter prescaler chooses prescale value N 1 8 64 256 or 1024 some modules support 32 and 128 but for this you will need to check the datasheet for the desired MCU Paremeter inverted is for choosing between inverted and non inverted PWM signal Parameter duty sets duty ratio from 0 to 255 PWM signal graphs f
34. 2 get ADC value from 2nd channel PORTB adc rd display rd 7 4 0 PORTC ade nd display adc rd 9 8 wend end 170 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection 9LVOAWLV ADC HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 171 CHAPTER 6 Libraries mikroBasic PRO for AVR CANSPI LIBRARY The SPI module is available with a number of the AVR compliant MCUs The mikroBasic PRO for AVR provides a library driver for working with mikroElektroni ka s CANSPI Add on boards with MCP2515 or MCP2510 via SPI interface The CAN is a very robust protocol that has error detection and signalization self checking and fault confinement Faulty CAN data and remote frames are re transmitted automatically similar to the Ethernet Data transfer rates depend on distance For example 1 Mbit s can be achieved at network lengths below 40m while 250 Kbit s can be achieved at network lengths below 250m The greater distance the lower maximum bitrate that can be achieved The lowest bitrate defined by the standard is 200Kbit s Cables used are shielded twisted pairs CAN supports two message formats Standard format with 11 identifier bits and Extended format with 29 identifier bits Note Consult the CAN standard about CAN bus termination resistan
35. MCU must module to use this library PWM Init must be called before using this routine MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 311 CHAPTER 6 Libraries mikroBasic PRO for AVR PWM Stop Stops the PWM MCU must have CMO module to use this library PWM Init and Start must be called before using this routine using this routine otherwise it will have no effect as the PWM module is not running Note Not all the AVR MCUs support both PWM and PWM1 library The best way to verify this is by checking the datasheet for the desired MCU Also you can check this by selecting a MCU in mikroBasic PRO for AVR looking at the Library Manager If library manager loads both PWM and PWM1 library you are able to check them then this MCU supports both PWM libraries Here you can take full advantage of our Code Assistant and Parameter Assistant feature of our compiler PWMI Init Prototvpe sub procedure PWM1 Init dim wave mode as byte dim prescaler as byte dim inverted as byte dim duty as byte Nothing Initializes the PWM module Parameter wave mode is a desired PWM mode There are two modes Phase Correct and Fast PWM Parameter prescaler chooses prescale value 1 8 64 256 or 1024 some modules support 32 and 128 but for this you will need to check the datasheet for the desired MCU Paremeter inverted is for choosing between inverted and non inverted PWM signal Parameter du
36. MMC SD card and MMC library must be initialized for file operations See Mmc Fat Init Requires The file must be previously assigned See Mmc Fat Assign dim my file size as longword main dion Mmc Fat Get File Size end 270 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc Fat Get Swap File Description sub function Mmc Fat Get Swap File dim sectors cnt as longint dim byref filename as string 11 dim file attr as byte as dword Number of the start sector for the newly created swap file if there was enough free space on the MMC SD card to create file of required size 0 otherwise This function is used to create a swap file of predefined name and size on the MMC SD media If a file with specified name already exists on the media search for consecutive sectors will ignore sectors occupied by this file There fore it is recommended to erase such file if it already exists before calling this function If it is not erased and there is still enough space for a new swap file this function will delete it after allocating new memory space for a new swap file The purpose of the swap file is to make reading and writing to MMC SD media as fast as possible by using the Mmc Read Sector and Mmc Write Sector functions directly without potentially damaging the FAT system The swap file can be considered as a window on
37. a neuvo tog is undefined Be careful when handling strings in this way since overwriting the end of a string will cause an unpredictable behavior Note mikroBasic PRO for AVR includes String Library which automatizes string related tasks MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 139 CHAPTER 5 Language Reference mikroBasic PRO for AVR POINTERS A pointer is a data type which holds a memory address While a variable accesses that memory address directly a pointer can be thought of as a reference to that memory address To declare a pointer data type add a carat prefix before type For example if you are creating a pointer to an integer you would write integer To access the data at the pointer s memory location you add a carat after the vari able name For example let s declare variable p which points to word and then assign the pointed memory location value 5 dim p as word A pointer can be assigned to another pointer However note that only address not value is copied Once you modify the data located at one pointer the other pointer when dereferenced also yields modified data Operator operator returns the address of a variable or routine i e constructs a pointer to its operand The following rules are applied to If x is a variable ex returns the address of x If is a routine a function or procedure returns F s entry point the
38. data data to be written data len number of bytes to be written MMC SD card and MMC library must be initialized for file operations See Fat Init The file must be previously assigned See Mmc Fat Assign The file must be opened for writing See Mmc Fat Rewrite or Mmc Fat Append dim file contents as char 42 main Mmc Fat Write file contents 42 write data to the assigned file end MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 267 CHAPTER 6 Libraries mikroBasic PRO for AVR Mmc Fat Set File Date sub procedure Mmc Fat Set File Date dim year as word dim month day hours mins seconds as byte Nothing Sets the date time stamp Any subsequent file write operation will write this stamp to the currently assigned file s time date attributs Prototype Parameters Description year year attribute Valid values 1980 2107 month month attribute Valid values 1 12 day day attribute Valid values 1 31 hours hours attribute Valid values 0 23 mins minutes attribute Valid values 0 59 seconds Seconds attribute Valid values 0 59 MMC SD card and MMC library must be initialized for file operations See Fat Init The file must be previously assigned See Mmc Fat Assign The file must be opened for writing See Mmc Fat Rewrite or Mmc Fat Append Example Fat Set File Date 2005 9 30 17 41 0 268 MIKROELEKTRONIKA SOFTWARE AND HARD
39. initialize TWI communication TWI Start issue TWI start signal TWI Write 0xA2 send byte via device address W TWI Write 2 send byte address of EEPROM location Write 0xAA send data data to be written TWI Stop issue TWI stop signal Delay 100ms Start issue TWI start signal TWI Write 0xA2 send byte via device address W TWI Write 2 send byte data address TWI Start issue TWI signal repeated start TWI Write 0xA3 send byt device address PORTA TWI Read 0 read data NO acknowledge TWI Stop issue TWI stop signal end HW Connection XTAL1 gt o Interfacing 24 02 to AVR via TWI 468 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries UART LIBRARY hardware module is available with a number of AVR MCUs mikroBasic PRO for AVR UART Library provides comfortable work with the Asynchronous full duplex mode You can easily communicate with other devices via RS 232 protocol for example with PC see the figure at the end of the topic RS 232 HW connection You need a AVR MCU with hardware integrated UART for example ATmega16 Then simply use the functions listed below Library Routines UARTx Init UARTx Init Advanced UARTx Data Ready UARTx Read UARTx Read Text UARTx Write UARTx Write Te
40. lt h1l gt AVR ENC28J60 Mini Web Server lt h1 gt lt a href gt Reload lt a gt lt script src s gt lt script gt lt table gt lt tr gt lt td valign top gt lt table border 1 style t chr 34 font size 20px font family terminal lt tr gt lt th colspan 2 gt PINC lt th gt lt tr gt scripto oar str ehr 34 ehzr 34 5 4 EOE IH0R 15 Of ac strt tchr 34 lt tr gt lt td bgcolor pink gt BUTTON lt toe ahr af PINCS 1 lt lt 1 str ehr 34 lt td bgcolor red gt ON chr 34 else str chr 34 lt td bgcolor cccccc gt OFF t chr 34 str chr 34 lt td gt lt tr gt chr 34 document write str lt script gt MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 383 CHAPTER 6 Libraries mikroBasic PRO for AVR const indexPage2 as stringi 466 lt table gt lt td gt lt td gt lt table border 1 style chr 34 font size 20px family terminal etr th colspan 3 gt PORTD lt th gt lt tr gt scripto yar etre str 4chr 34 tchr 34 4 for i 0 i c8 i44 strt t chr 34 lt tr gt lt td bgcolor yellow gt L chr 34 i cehr 34 lt td gt ehr 34 4 if PORTD amp 1 lt lt i str ehr 34 lt td D bgcolor recd ON ehr 3
41. sub procedure Expander Write PortA dim ModuleAddress as byte dim Data as byte Description The function writes byte to Port Expander s PortA Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written Port Expander must be initialized See Expander Init Port Expander s PortA should be configured as output See Expander Set DirectionPortA and Expander Set DirectionPortAB routines Write a byte to Port Expander s PORTA Expander Set DirectionPortA 0 0x00 set expander s porta to be output Expander Write PortA 0 OxAA MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Expander Write PortB sub procedure Expander Write PortB dim ModuleAddress as byte dim Data as byte The function writes byte to Port Expander s PortB Prototype Parameters Description ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written Port Expander must be initialized See Expander Init Port Expander s PortB should be configured as output See Expander Set DirectionPortB and Expander Set DirectionPortAB routines Write a byte to Port Expander s PORTB Expander Set DirectionPortB 0 0x00 set expander s portb to be output Expander Write PortB 0 0x55 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR E
42. Assembler File asm extracted from the List File Assembly View After compiling the program in the mikroBasic PRO for AVR you can click the View Assembly icon or select Project gt View Assembly from the drop down menu to review the generated assembly code asm file in new tab window Assembly is human readable with symbolic names Related topics Project Menu Project Toolbar Error Window Project Manager Pro ject Settings MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 77 CHAPTER 2 Environment mikroBasic PRO for AVR ERROR MESSAGES Compiler Error Messages Ss is not valid Unknown Me na Identifier 5 was declared Syntax error Expected ss but ss found Argument is out of range 25 Syntax error in additive GNIS SIGNE File ss not found Invalid omit ond Woe Not enough A Too many parameters Too many characters Actual and formal parameters must be identical Invalid ASM instruction ss Identifier s has been already declared in Syntax error in multiplicative expression Definition file for s is corrupted ORG directive is currently supported for interrupts only Not enough ROM Not enough RAM External procedure s used in ss was not found Internal error ss Unit cannot recursively use itself 5s cannot be used out of loop Supplied and formal parameters do not match s to s Co
43. Description Parameters remoteHost Client s IP address remotePort client s TCP port localPort port to which the request is sent reqLength TCP HTTP request data field length Note The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply Requires Ethernet module has to be initialized See Spi Ethernet Init This function is internally called by the library and should not be called by the user s code MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 379 CHAPTER 6 Libraries mikroBasic PRO for AVR Spi Ethernet UserUDP sub function Spi Ethernet UserUDP dim remoteHost as byte dim remotePort as word dim destPort as word dim reqLength as word as word 0 there should not be a reply to the request Length of UDP reply data field otherwise This is UDP module routine It is internally called by the library The user accesses to the UDP request by using some of the Spi Ethernet get routines The user puts data in the transmit buffer by using some of the Spi Ethernet put routines The function must return the length in bytes of the UDP reply or 0 if nothing to transmit If you don t need to reply to the UDP requests just define this function with a return O as single statement Parameters Description remoteHost Client s IP address remotePort client s port destPort port to whic
44. Identifiers 7 are not case sensitive and have a specific namespace You override them with your own members 7 within any given structure See Predefined Globals and Constants for more information on register bit names sbit type The mikroBasic PRO for AVR compiler has sbit data type which provides access to bit addressable SFRs You can access them in several ways dim LEDA as sbit at PORTA BO dim Name as sbit at sfr name B bit position dim LEDB as sbit at 0 dim Name as sbit at sfr name lt bit position gt 90 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroBasic PRO for AVR Specifics bit type The mikroBasic PRO for AVR compiler provides a bit data type that may be used for variable declarations It can not be used for argument lists and function return values dim bf as bit bit variable There are no pointers to bit variables dim etr as ptt V invalid An array of type bit is not valid dtim arr as arrayt so ott y Note Bit variables can not be initialized Bit variables can not be members of structures Bit variables do not have addresses therefore unary operator e address of is not applicable to these variables Related topics Predefined globals and constants MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 91 CHAPTER 3 Specifics mikroBasic PRO for AVR INTERRUPTS AVR deriv
45. Man Send 0 0 Send end byte Delay ms 1000 wend end Connection Example Transmitter RF module Antenna gt j Y m vcc A RT4 n GND Simple Transmitter connection Receiver RF module Antenna 9LVOANLV Simple Receiver connection 254 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries MULTI MEDIA CARD LIBRARY The Multi Media Card MMC is a flash memory card standard MMC cards are cur rently available in sizes up to and including 1 GB and are used in cell phones mp3 players digital cameras and PDA s mikroBasic PRO for AVR provides a library for accessing data on Multi Media Card via SPI communication This library also supports SD Secure Digital memory cards Secure Digital Card Secure Digital SD is a flash memory card standard based on the older Multi Media Card MMC format SD cards are currently available in sizes of up to and including 2 GB and are used in cell phones mp3 players digital cameras and PDAs Notes Routines for file handling can be used only with FAT16 file system Library functions create and read files from the root directory only Library functions populate both FAT1 and FAT2 tables when writing to files but the file data is being read from the FAT1 table only i e there is no recovery if FAT1 tab
46. SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Library Routines Soft SPI Init Soft SPI Read Soft SPI Write Soft SPI Init Prototype sub procedure Soft SPI Init CHAPTER 6 Libraries Nothing Configures and initializes the software SPI module Global variables Chip Select So0ft5pt 6015 SoftSpi SDO LK SoftSptr C Select SoftSpi SDI Direction Direction of the Data in pin SoftSpi SDO Direction Direction of the Data out pin S0ft5pr LK Chip select line Data in line Data out line Data clock line Direction Direction of the Chip select pin Direction Direction of the Data clock pin must be defined before using this function soft spi pinout defination dim Chip Select as sbit at PORTB BO dim SoftSpi SDI as sbit at PINB B6 dim SoftSpi SDO as sbit at PORTB B5 dim SoftSpi CLK as sbit at PORTB B7 dim Chip Select Direction as sbit at DDRB BO dim SoftSpi SDI Direction as sbit at DDRB B6 dim SoftSpi SDO Direction as sbit at DDRB B5 dim SoftSpi CLK Direction as sbit at DDRB B7 end of soft pinout d finition Soft SPI T Inst Soft SPI MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 347 CHAPTER 6 Libraries mikroBasic PRO for AVR Soft SPI Read Prototype sub function Soft SPI Read dim sdata as byte as word Byte received via the SPI bus This routine performs
47. SPI Port Expander 5 RS 485 UART SPI Ethernet 5 Ethernet Api gt Trigonometry sei String Port Expander gt SPI 1 Port Expander SPI Port Expander gt Constans A Port Expander J sr 7 169 CHAPTER 6 Libraries mikroBasic PRO for AVR ADC LIBRARY ADC Analog to Digital Converter module is available with a number of AVR micros Library func tion ADC Read is included to provide you comfortable work with the module in single ended mode ADC Read Prototype sub function ADC Read dim channel as byte as word Returns 10 bit or 12 bit MCU dependent unsigned value from the specified 1 Initializes AVR s internal ADC module to work with XTAL frequency prescaled by 128 Clock determines the time period necessary for performing A D conver sion Description Parameter 1 represents the channel from which the analog value is to be acquired Refer to the appropriate datasheet for channel to pin mapping dim tmp as word tmp Read 2 Read analog value from channel 2 Library Example This example code reads analog value from channel 2 and displays it on PORTB and PORTC program ADC on LEDs dim adc rd as word main DDRB OxFF Set PORTB as output DDRC OxFF Set PORTC as output while TRUE temp res ADC
48. SPI T6963C ClearBit SPI T6963C SetBit SPI T6963C NegBit SPI T6963C DisplayGrPanel SPI T6963C DisplayTxtPanel SPI T6963C SetGrPanel SPI T6963C SetTxtPanel SPI T6963C PanelFill SPI T6963C GrFill SPI T6963C TxtFill SPI T6963C Cursor Height SPI T6963C Graphics SPI T6963C Text SPI T6963C Cursor SPI T6963C Cursor Blink MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 421 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI T6963C Config sub procedure SPI T6963C Config dim width as word dim height as word dim fntW as word dim DeviceAddress as byte dim wr as byte dim rd as byte dim cd as byte dim rst as byte Initalizes the Graphic Lcd controller Parameters width Width of the Glcd panel height height of the Glcd panel fntw font width DeviceAddress SPI expander hardware address see schematic at the bottom of this page wr write signal pin on Glcd control port rd read signal pin on Glcd control port command data signal pin on Glcd control port rst reset signal pin on Glcd control port Display RAM organization The library cuts RAM into panels a complete panel is one graphics panel fol lowed by a text panel see schematic below Description Schematic 422 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Global variables SPExpande
49. You can include one file per include clause There can be any number of the include clauses in each source file but they all must be stated immediately after the pro gram or module name Here s an example program MyProgram imeluee utils include strings include MyUnit For the given module name the compiler will check for the presence of mcl and mbas files in order specified by search paths If both mbas and 1 files are found the compiler will check their dates and include the newer one in the project If the mbas file is newer than the mci then mbas file will be recompiled and new 1 will be created overwriting the old 1 If only the mbas file is found the compiler will create the mc1 file and include it in the project If only the 1 file is present i e no source code is available the compiler will include it as found If none of the files found the compiler will issue a File not found warning 124 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference Main Module Every project in mikroBasic PRO for AVR requires a single main module file The main module is identified by the keyword program at the beginning It instructs the compiler where to start After you have successfully created an empty project with Project Wizard Code Edi tor will display a new main module It contains the bare bones of
50. for MCUs with 64kb of Flash memory or less sub function FLASH Read Byte dim address as word as byte for MCUs with Flash memory larger than 64kb sub function FLASH Read Byte dim address as longword as byte Returns Returns data byte from Flash memory Reads data from the specified address in Flash memory for MCUs with Flash memory larger than 64kb dim tmp as longword tmp Flash 0 0 00 214 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries FLASH Read Bytes for MCUs with 64kb of Flash memory or less sub procedure FLASH Read Bytes dim address as word dim buffer as byte dim NoBytes as word Prototype for MCUs with Flash memory larger than 64kb sub procedure FLASH Read Bytes dim address as longword dim buffer as byte dim NoBytes as word Description Reads number of data bytes defined by NoBytes parameter from the specified P address in Flash memory to varibale pointed by buffer for MCUs with Flash memory larger than 64kb const F ADDRESS as longint 0x200 dim dat buff 32 as word FLASH Read Bytes F ADDRESS dat buff 64 FLASH Read Word for MCUs with 64kb of Flash memory or less sub function FLASH Read Word dim address as word as word Prototype for MCUs with Flash memory larger than 64kb sub function FLASH Read Word dim address as longword as word Returns data word from Flash memory R
51. x pos X position Valid values 0 127 y pos y position Valid values 0 63 Description color color parameter Valid values 0 2 The parameter color determines a dot state 0 clears dot 1 puts a dot and 2 inverts dot state Note For x and y axis layout explanation see schematic at the bottom of this page Requires Glcd needs to Glcd needs to be initialized see Glod Initrouine initialized see Glcd Init routine Invert E are in the upper left corner Glcd Dot Glcd Line sub procedure Glcd Line dim x start as integer dim y start as inte ger dim x end as integer dim y end as integer dim color as byte Draws a line on Glcd Parameters x start X coordinate of the line start Valid values 0 127 y start y coordinate of the line start Valid values 0 63 x end X coordinate of the line end Valid values 0 127 y end y coordinate of the line end Valid values 0 63 color COlor parameter Valid values 0 2 Description The parameter color determines the line color O white 1 black and 2 inverts each dot Requires Glcd needs to be initialized see Glcd Init routine Draw a line between dots 0 0 20 30 1 Line 0 0 20 30 1 224 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Glcd V Line Prototype sub procedure Glcd V Line dim y start as byte dim y end as byte yp dim x pos as
52. 100 wend end 300 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection Port Expander HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 301 CHAPTER 6 Libraries mikroBasic PRO for AVR PS 2 LIBRARY The mikroBasic PRO for AVR provides a library for communication with the common PS 2 keyboard Note The library does not utilize interrupts for data retrieval and requires the oscil lator clock to be at least 6 2 Note The pins to which a PS 2 keyboard is attached should be connected to the pull up resistors Note Although PS 2 is a two way communication bus this library does not provide MCU to keyboard communication e g pressing the Caps Lock key will not turn on the Caps Lock LED External dependencies of PS 2 Library The following variables must be defined in all projects using PS 2 Library dim PS2 Data as sbit s 2 as sbit dim PS2 In Clock as 2 dim 52 Clock as sbit sfr external PS 2 Clock line in it at PINC B1 Description dim PS2 Out Clock as 1 PS2 Out Clock as sbit sfr external PS 2 Clock line out i PORTC BO oan Direction of the PS 2 Data PS2 Data Direction as _Direction as sbit sfr external pin i DDRC BO dim dim PSS Clock Direction Ss PS2 Clock Direction as sbit sfr external as sbit at DDRC B1 Library Routines
53. 66 VI MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Table of Contents Metacharacters Backreferences 66 mikroBasic PRO for AVR Command Line Options 67 PEOJOCIS OR URDU Re 68 New Project i2 dise ge Wer fe RR A eee rb rt 68 New Project Wizard Steps 69 Customizing Projects 72 Edit Project ce Bann deerit a ad RAT ede 72 Managing Project Group 72 Add Remove Files from 72 Project Level 73 SUA c D a Daa 74 Managing Source Files 74 Creating new source file 74 Opening an existing 74 Printing an 74 Saving aure ap ade DR E RR We aed aga 75 Saving file under a different name 75 Closing Tile 5 rre obe Sene RUNE p ded UR ue LR pen 75 Clean Project Folder 76 Clean Project Folder 76 Compilation s a sett pr
54. CAN message identifier Valid values 11 or 29 bit values depending on message type standard or extended wr data data to be sent an array of bytes up to 8 bytes in length data len data length Valid values 1 to 8 CAN RX MSG FLAGS message flags The CANSPI module must be in mode in which transmission is possible See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page send messag xtended CAN message with the appropriate ID and data dim tx flags as byte rd data bytel 8 msg id as longint CANSPISetOperationMode CAN MODE NORMAL OxFF set NORMAL mode CANSPI must be in mode in which transmission is possible tx flags CANSPI TX PRIORITY 0 CANSPI TX XTD FRAME set message flags CANSPIWrite msg id rd data 2 tx flags MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 181 CHAPTER 6 Libraries mikroBasic PRO for AVR CANSPI Constants There is a number of constants predefined in the CANSPI library You need to be familiar with them in order to be able to use the library effectively Check the exam ple at the end of the chapter CANSPI OP MODE The CANSP OP MODE constants define CANSPI operation mode Function CANSPISetOperationMode expects one of these as it s argument
55. CHAPTER 6 Libraries mikroBasic PRO for AVR Cf Read Init sub procedure Cf Read Init dim address as longword dim sector count as byte Prototype Initializes CF card for reading Description Parameters address the first sector to be prepared for reading operation sector count number of sectors to be prepared for reading operation c Durs MCU ports must be appropriately initialized for CF card See initialize compact flash for reading from sector 590 Example Read Inrt 590 1 Cf Read Byte Prototype sub function CF Read Byte as byte Returns a byte read from Compact Flash sector buffer Note Higher byte of the unsigned return value is cleared Reads one byte from Compact Flash sector buffer location currently pointed to Description by internal read pointers These pointers will be autoicremented upon reading The corresponding MCU ports must be appropriately initialized for CF card See Cf Init Requires CF card must be initialized for reading operation See Cf Read Init Read byte from compact flash dim data as byte data Cf Read Byte 194 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Cf Write Init sub procedure Cf Write Init dim address as longword dim sectcnt Prototype as byte Initializes CF card for writing 22 Parameters Description address the first sector to be prepa
56. CHAPTER 6 Libraries mikroBasic PRO for AVR PWM LIBRARY CMO module is available with a number of AVR MCUs mikroBasic PRO for AVR provides library which simplifies using PWM HW Module Note For better understanding of PWM module it would be best to start with the example provided in Examples folder of our mikroBasic PRO for AVR compiler When you select a MCU mikroBasic PRO for AVR automaticaly loads the correct PWM library or libraries which can be verified by look ing at the Library Manager PWM library handles and initializes the PWM module on the given AVR MCU but it is up to user to set the correct pins as PWM output this topic will be covered later in this section mikroBasic PRO for AVR does not support enhanced PWM modules Library Routines PWM Init PWM Set Duty PWM Start PWM Stop PWMI Init PWM1 Set Duty 1 Start PWM1 Stop Predefined constants used in PWM library The following variables are Dasenpiton used in functions Selects Phase Correct PWM mode on first PWM library Selects Phase Correct PWM mode on second PWM library if it exists in Library Manager Selects Fast PWM mode on first PWM library CO Selects Fast PWM mode on second PWM library if it exists in Library Manager Sets prescaler value to 1 No prescaling Sets prescaler value to 8 Sets prescaler value to 32 this value is not available
57. COlor parameter Valid values 0 2 The parameter color determines the line color O white 1 black and 2 inverts each dot Glcd needs to be initialized for SPI communication see Glcd Init routines Example Draw a horizontal line between dots 10 20 and 50 20 SPI Gled H Line 10 50 20 1 396 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI Glcd Rectangle sub procedure SPI Glcd Rectangle dim x upper left as byte dim y upper left as byte dim x bottom right as byte dim y bottom right as byte dim color as byte Draws a rectangle on Glcd Parameters x upper left X coordinate of the upper left rectangle corner Valid values 0 127 upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right X coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 color color parameter Valid values 0 2 Description The parameter color determines the color of the rectangle border 0 white 1 black and 2 inverts each dot Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Draw a rectangle between dots 5 5 and 40 40 SPI Gled Rectangle 5 5 40 40 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 397 CHAPTER 6 Libraries
58. E Led mel F Led user dic 7 Lcd wch Clean Cancel C Program Files Mikroelektronika mikroBasic PRO for AVR Examples Led MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment COMPILATION When you have created the project and written the source code it s time to compile it Select Project Build from the drop down menu or click the Build Icon 5 from the Project Toolbar If more more than one project is open you can compile all open projects by selecting Project Build All from the drop down menu or click the Build All Icon 2 from the Project Toolbar Progress bar will appear to inform you about the status of compiling If there are some errors you will be notified in the Error Window If no errors are encountered the mikroBasic PRO for AVR will generate output files Output Files Upon successful compilation the mikroBasic PRO for AVR will generate output files the project folder folder which contains the project file Output files are summarized in the table below Intel style hex records Use this file to program Intel HEX AVR MCU he Binar mikro Compiled Library Binary distribution of y application that can be included in other projects x M Overview of AVR memory allotment instruction List File addresses registers routines and labels Human readable assembly with symbolic names
59. PHSEG1 as defined in CAN controller s datasheet PHSEG2 as defined in CAN controller s datasheet PROPSEG as defined in CAN controller s datasheet CAN CONFIG FLAGS is formed from predefined constants see CANSPI constants Global variables CanSpi 5 Chip Select line CanSpi Rst Reset line CanSpi CS Bit Direction Direction of the Chip Select pin CanSpi Rst Bit Direction Direction of the Reset pin must be defined before using this function The CANSPI routines are supported only by MCUs with the SPI module The SPI module needs to be initialized See the SPI1 Init and SPI1 Init Advanced routines MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page 175 CHAPTER 6 Libraries mikroBasic PRO for AVR CANSPI module connections dim CanSpi CS as sbit at PORTB BO CanSpi CS Direction sbit at DDRB BO CanSpi Rst as sbit at PORTB B2 CanSpi Rst Direction as sbit at DDRB B2 End CANSPI module connections dim Can Init Flags as byte Can Init Flags CAN CONFIG SAMPLE THRICE and form value to be used CAN CONFIG PHSEG2 PRG ON and with CANSPIInitialize CAN CONFIG XTD MSG and CAN CONFIG DBL BUFFER ON and CAN CONFIG VALID XTD MSG Spi Rd Ptr SPI1 Read Pass pointer to SPI Read func tion of used SPI module 5 1 Init f SPI module GANSPIInrtialize 1 9 3 9 1 Can Init
60. SPLGled H Line loc LO Inaccessible y pos FARG SPI Gled H Line 2 Inaccessible x stat FARG SPI Glcd H Line 0 Inaccessible x end SPI Gled H Line 1 Inaccessible data out FARG SPI1 Read 0 Inaccessible color FARG_SPI_Gled_V_Line 3 Inaccessible loc SPI Gled V Line loc 110 Inaccessible x pos FARG_SPI_Gled_V_Line 2 Inaccessible y_start SPI Glcd V Line 0 Inaccessible FARG_SPI_Gled_V_Line 1 _SPI_Glcd ROM Memory ROM Memory Usage Displays ROM memory usage in form of histogram 4 Memory Usage j MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 49 CHAPTER 2 Environment mikroBasic PRO for AVR ROM Memory Allocation Displays ROM memory allocation 4 Memory Usage 0 0000 0 0 942 0 0004 0 0 9400 0 0008 0 0 9400 0 000 OxOC9400 0 0010 0 0 9400 0 0014 OxOC9400 0 0018 0 0 9400 0 001 OxOC9400 0 0020 0 0 9400 0 0024 0 0 9400 0 0028 0 0 9400 0 002 0 0 9400 0 0030 0 0 9400 0 0034 0 0 9400 0 0038 OxOC9400 0 003 OxOC9400 0 0040 0 0 9400 0 0044 OxOC9400 0 0048 OxOC9400 0 004 0 0 9400 0 0050 0 0 9400 0 15 2 0 22 5 xl5F4 OxlBE2 0 15 6 0 00 0 0 15 0 0 5 0 15 1 xl5FC 0 1 95 4 Procedures Windows Provides overview proc
61. Select Case Statement Iteration Statements Loops For Statement While Statement Do Statement Jump Statements Break and Continue Statements Exit Statement Goto Statement Gosub Statement asm Statement Directives Compiler Directives Linker Directives LEXICAL ELEMENTS OVERVIEW These topics provide a formal definition of the mikroBasic PRO for AVR lexical ele ments They describe different categories of word like units tokens recognized by the language In tokenizing phase of compilation the source code file is parsed that is broken down into tokens and whitespace The tokens in mikroBasic PRO are derived from a series of operations performed on your programs by the compiler A mikroBasic PRO program starts as a sequence of ASCII characters representing the source code created by keystrokes using a suitable text editor such as the mikroBasic PRO Code Editor The basic program unit in mikroBasic PRO is a file This usually corresponds to a named file located in RAM or on disk having the extension mbas MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 111 CHAPTER 5 Language Reference mikroBasic PRO for AVR WHITESPACE Whitespace is a collective name given to spaces blanks horizontal and vertical tabs and comments Whitespace serves to indicate where tokens start and end but beyond this function any surplus whitespace is discarded For example the two sequences dim tmp as byte dim j a
62. TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example SPI T6963C Write Char A 22 23 AND 426 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR CHAPTER 6 Libraries SPI T6963C Write Text Prototype Description Requires MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD sub procedure SPI T6963C Write Text dim byref str as byte 10 dim x as byte dim y as byte dim mode as byte Nothing Writes text in the current text panel of Glcd at coordinates x y Parameters str text to be written x text position on x axis y text position on y axis node mode parameter Valid values SPI TG963C ROM MODE OR SPI T6963C ROM MODE T6963C ROM MODE AND and SPI T6963C ROM MODE TEXT Mode parameter explanation OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in negative mode i e white text on black background AND Mode The te
63. b and a is extended with zeroes b becomes 00A0 Signed and Conversions If number is converted from less complex to more complex data type the upper bytes are filled with ones if sign bit is 1 number is negative the upper bytes are filled with zeroes if sign bit is 0 number is positive If number is converted from more complex to less complex data type the data is simply truncated the upper bytes are lost For example dim a as byte dim b as word a 12 b 70FF b b and a a is sign extended upper byte is FF becomes 70F4 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 149 CHAPTER 5 Language Reference mikroBasic PRO for AVR Bitwise Shift Operators The binary operators lt lt and gt gt move the bits of the left operand by a number of positions specified by the right operand to the left or right respectively Right operand has to be positive and less than 255 With shift left lt lt left most bits are discarded and new bits on the right are assigned zeroes Thus shifting unsigned operand to the left by n positions is equiv alent to multiplying it by 2n if all discarded bits are zero This is also true for signed operands if all discarded bits are equal to the sign bit With shift right gt gt right most bits are discarded and the freed bits on the left are assigned zeroes in case of unsigned operand or the value of the sign bit in case of signed oper
64. c 118 eoe mo OUR One Ove C 119 Bos 119 Program Organization 120 Organization of Main Module 120 Organization of Other Modules 121 Scope and Visibility 123 SCOPE seb Oed da td rb debet oS e Nee woe hee 123 ede ace pain COO TRA UR 123 Modules he eee heh ae eh x URGE ieee RE 124 Include Clause 124 Main Module uses pate pde hb RR Ve i Rue her Oe 125 Other Modules 125 Interface Section 125 Implementation Section 126 Variables ie Ptol de Sa aks panne ORI 127 Variables and 127 de P 128 Labels ELEC Ie RC Peace 129 Suppe 130 Functions and 131 FUNCUONS iuo cob vete ieee aep ae ba Ga aches 131 Calling a f nctl n sse e eae PEE eee CE d 131 Le ace UE XE EUR ee oe 132 PrOCedUres secu Ra d EHE a AUG RENE RR EEG d 132 Calling a procedure 132
65. dat buff word 32 main DDRD OxFF set direction to be output DDRB OxFF set direction to be output word data 0 link const table 216 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries counter 0 while counter lt 64 reading 64 bytes in loop PORTD FLASH Read Byte F ADDRESS counter demonstration of reading single byte Inc counter PORTB FLASH Read Byte F ADDRESS counter demonstration of reading single byte Inc counter Delay ms 200 wend FLASH Read Bytes F ADDRESS dat buff 64 demonstration of reading 64 bytes for counter 0 to 31 PORTD dat buff counter output low byte to PORTD PORTB word dat buffi counter gt gt 8 output er byte to PORTB Delay ms 200 next counter counter 0 while counter lt 63 reading 32 words in loop word FLASH Read Word F ADDRESS counter demonstration of reading single word PORTD word _ output low byte to PORTD PORTE Hi word gt gt 8 output higher byte to PORTB counter counter 2 Delay ms 200 wend FLASH Read Words F ADDRESS buff 32 demonstration of reading 64 bytes for counter 0 to 31 PORTD dat buff counter output low byte to PORTD PORTB word dat buff counter gt gt 8 output Hugh er byte to PORTB Delay ms 200 next counter end MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOL
66. data it merely allows copying of source to destination For example dim a as byte dim b as short b 1 a byte b vU d ome 858 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 assignment operator word b a Compiler will report an error 144 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference OPERATORS Operators are tokens that trigger some computation when being applied to variables and other objects in an expression There are four types of operators in mikroBasic PRO for AVR Arithmetic Operators Bitwise Operators Boolean Operators Relational Operators OPERATORS PRECEDENCE AND ASSOCIATIVITY There are 4 precedence categories in mikroBasic PRO for AVR Operators in the same category have equal precedence with each other Each category has an associativity rule left to right or right to left In the absence of parentheses these rules resolve the grouping of expressions with oper ators of equal precedence Precedence LIII MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 145 CHAPTER 5 Language Reference mikroBasic PRO for AVR ARITHMETIC OPERATORS Arithmetic operators are used to perform mathematical computations They have numer ical operands and ret
67. dot position on y axis color COlor parameter Valid values T6963C BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C Init routine Example T6963C Dot x0 0 pcolor 448 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries T6963C Write Char Prototype Description sub procedure T6963C Write Char dim c x y mode as byte Nothing Writes a char in the current text panel of Glcd at coordinates x y Parameters c char to be written x char position on x axis y Char position on y axis node mode parameter Valid values 6963 ROM MODE OR T6963C ROM MODE XOR T6963C ROM MODE AND and T6963C ROM MODE TEXT Mode parameter explanation OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in the negative mode i e white text on black background AND Mode The text and graphic data shown on display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet
68. main ADCSRA 7 0 Set AN pins to Digital I O PORTC 0 DDRC 255 Can Init Flags 0 Can Send Flags 0 elear flags Can Rcv Flags 0 Can Send Flags CANSPI TX PRIORITY 0 and form value to be used CANSPI TX XTD FRAME and with CANSPIWrite CANSPI TX NO RTR FRAME Can Init Flags CANSPI CONFIG SAMPLE THRICE and form value to be used CANSPI CONFIG PHSEG2 PRG ON and with CANSPIInit CANSPI CONFIG XTD MSG and CANSPI CONFIG DBL BUFFER ON and CANSPI CONFIG VALID XTD MSG MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 185 CHAPTER 6 Libraries mikroBasic PRO for AVR Dna initialize SPI1 module Spi_Rd Ptr SPI1 Read i Pass pointer to SPI Read sub function of used SPI module CANSPI initialize 1 37 3739 1 Flags Initialize external CANSPI module CANSPISetOperationMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPISetMask CANSPI MASK 1 1 CANSPI CONFIG XTD MSG i set all maskl bits to ones CANSPISetMask CANSPI MASK B2 1 CANSPI CONFIG XTD MSG set all mask2 bits to ones CANSPISetFilter CANSPI FILTER B2 F4 3 CANSPI CONFIG XTD MSG y Set sd GE filter Xo 9 CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode RxTx Data 0 9 set initial data to be sent Tx ID 12111 set transmit ID CANSPIWrite Tx ID RxTx Data 1 Can Send Fla
69. statements are executed repeatedly until expression evaluates true expression is evaluated after each iteration so the loop will execute statements atleast once Here is an example of calculating scalar product of two vectors using the do statement 5 0 0 s s bf i po odo loop until i n JUMP STATEMENTS A jump statement when executed transfers control unconditionally There are five such statements in mikroBasic PRO for AVR break continue exit goto gosub MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference BREAK AND CONTINUE STATEMENTS Break Statement Sometimes you might need to stop the loop from within its body Use the break statement within loops to pass control to the first statement following the innermost loop for while or do For example Led Ogt l 1 No card inserted Wait for CF card to be plugged refresh every second while true if Cf Det ct 1 then break end if Delay ms 1000 wend Now we can work with CF card Lcd Out 1 1 Card detected y Continue Statement You can use the continue statement within loops to skip the cycle continue Statement in the for loop moves program counter to the line with keyword for continue Statement in the while loop moves program counter to the line with loop condition top of the loop continue Statement in th
70. strncpy strspn strcspn strnomp strpbrk strrchr strstr memchr sub function memchr dim p as byte dim ch as byte dim n as Prototype word as word The function locates the first occurrence of the word ch in the initial n words of memory area starting at the address The function returns the offset of this occurrence from the memory address p or oxrrrr if ch was not found Description For the parameter p you can use either a numerical value literal variable con stant indicating memory address or a dereferenced value of an object for example mystring PORTB MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 489 CHAPTER 6 Libraries mikroBasic PRO for AVR memcmp Prototype sub function memcmp dim 1 p2 as byte dim n as word as integer The function returns a positive negative or zero value indicating the relation ship of first n words of memory areas starting at addresses p1 and p2 This function compares two memory areas starting at addresses and for n words and returns a value indicating their relationship as follows Meaning pl less than p2 Description pl equal to p2 pl greater than p2 The value returned by the function is determined by the difference between the values of the first pair of words that differ in the strings being compared For parameters p1 and p2 you can use either a numerical value literal vari able constant indicating me
71. 0 while s result lt gt 0 SPI Ethernet putByte sf result Inc result wend end sub k this sub function is called by the library the user accesses to the HTTP request by successive calls to SPI Ethernet getByte the user puts data in the transmit buffer by successive calls to SPI Ethernet putByte the sub function must return the length in bytes of the HTTP reply or 0 if nothing to transmit if you don t need to reply to HTTP requests just define this sub function with a return 0 as single state ment sub function Spi Ethernet UserTCP dim byref remoteHost as byte 4 dim remotePort localPort reqLength as word as word dim len word my reply length bitMask as byte for bit mask tmp as byte 5 to copy const array to ram for memcmp lem 0 if localPort lt gt 80 then I listen only to web request on port 80 result 0 exit end if get 10 first bytes only of the request the rest does not mat ter here for lem 0 40 9 getRequest len SPI Ethernet getByte next len getBequest Len Q 0 while httpMethod len lt gt 0 len 1 httpMethod len 1 ine Len wend MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 385 CHAPTER 6 Libraries mikroBasic PRO for AVR if memcmp getRequest tmp 5 lt gt 0 then only GET method is supported here result 0 exit end if httpCounter httpC
72. 0 000001234 FloatToSEr ffl txt T ezt ie 2 PloatToStr ff2 txt v txt is 123 4567 PlostToStr ff3 txt txt is 1 234e 6 482 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Dec2Bcd Prototype sub function Dec2Bcd dim decnum as byte as byte Returns Converted BCD value Converts input number to its appropriate BCD representation Description Parameters decnum number to be converted dim a b as byte 22 Dec2Bcd a b equals 34 Bcd2Dec16 Prototype sub function Bcd2Decl6 dim bcdnum as word as word Returns Converted decimal value Converts 16 bit BCD numeral to its decimal equivalent Description Parameters bcdnum 16 bit BCD numeral to be converted dim a b as word 0x1234 equals 4660 2 16 a b equals 1234 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 483 CHAPTER 6 Libraries mikroBasic PRO for AVR Dec2Bcd16 Prototype sub function Dec2Bcdl6 dim decnum as word as word Returns Converted BCD value Converts decimal value to its BCD equivalent Description Parameters decnum decimal number to be converted a b as word 2345 Dec2Bcd16 a b equals 9029 484 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries MATH LIBRARY The mikroBasic PRO for AVR provides a set of
73. 120 T6963C cirele 120 T6963C sprite 76 4 T6963C_setGrPanel 1 T6963C_image mikroe while TRUE panel 0 and graphic 1 if PINAO bit Inc panel panel 0 239 2395 127 0 8 10 30 50 Ts 90 1105 130 einstein If PORTA 0 is pressed then panel and 1 CHAPTER 6 Libraries T6963C WHITE T6963C WHITE T6963C WHITE 123 T6963C WHITE T6963C WHITE T6963C WHITE T6963C WHITE E T6963C WHIT T6963C WHIT T6963C WHIJ T6963C WHIJ d d gt B8 119 Draw a sprite Select other graphic panel Endless loop toggle the display between graphic T6963C setPtr T6963C grMemSize T6963C txtMemSize panel T6963C GRAPHIC HOME ADDR ESS SF T Delay ms 300 else 3f PINA1 bit T6963C text 0 Delay ms 300 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 0 If PORTA 1 is pressed display only graphic panel then T6963C 1 461 CHAPTER 6 Libraries mikroBasic PRO for AVR If PORTA 2 is pressed display only text panel else if PINA2 bit 0 then T6963C graphics 0 T6963C text 1 Delay ms 300 If PORTA 3 is pressed display text and graphic panels else if PINAS bit 0 then T6963C graphics 1 T6963C text 1 Delay ms 300
74. 2 Write string delay2S wend end 232 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection o Left side Right side X axis vcc all Adjustment ve rd LI Glcd HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 233 CHAPTER 6 Libraries mikroBasic PRO for AVR KEYPAD LIBRARY The mikroBasic PRO for AVR provides a library for working with 4x4 keypad The library routines can also be used with 4x1 4x2 or 4x3 keypad For connections explanation see schematic at the bottom of this page Note Since sampling lines for AVR MCUS are activated by logical zero Keypad Library can not be used with hardwares that have protective diodes connected with anode to MCU side such as mikroElektronika s Keypad extra board HW Rev v1 20 The following variable must be defined in all f Description projects using Keypad Library dim keypadPort as dim keypadPort as byte sfr external Keypad Port byte at PORTB di Direction of the keypadPort Direction P 1 eypad keypadPort Direction as byte sfr external as byte at DDRB Library Routines Keypad Init Keypad Key Press Keypad Key Click 234 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Keypad Init Initializes po
75. 3 operations simultaneously It provides clock for the Soft ware SPI bus reads a byte and sends a byte Deseripton Parameters sdata data to be sent Soft SPI must be initialized before using this function See Soft SPI Init routine dim data read as byte data send as byte Read a byte and assign it to data read variable data send byte will be sent via SPI during the Read operation data read Soft SPI Read data send Soft SPI Write Prototype sub procedure Soft SPI Write dim sdata as byte This routine sends one byte via the Software SPI bus Description Parameters sdata data to be sent Requires Soft SPI must be initialized before using this function See Soft SPI Init routine Write a byte to the Soft SPI bus Soft SPI Write 0xAA 348 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example This code demonstrates using library routines for Soft SPI communication Also this example demonstrates working with Microchip s MCP4921 12 bit D A converter program Soft SPI DAC module connections dim Chip Select as sbit at PORTB 0 SoftSpi CLK as sbit at 7 SoftSpi SDI as sbit at PINB 6 Note Input signal SoftSpi SDO as sbit at PORTB 5 dim Chip Select Direction as sbit at DDRB 0 SoftSpi CLK Direction as sbit at DDRB 7 SoftSpi SDI Direction as sbit at DDRB 6 SoftSpi SDO Direction as sbit at DD
76. 52 Direction 9 pin as sbit at DDRD B2 Enable direction pin 25 1 D it at DDR dim LCD D7 Direction Data 7 direction pin Es bib sb DUO OU irection DRD B3 LCD bi EN Data 5 direction dim LCD D5 Direction as sbit at DDRD B6 LCD D4 dim Data 6 direction pin dim LCD D6 Direction a Opin as sbit at DDRD B5 as sbit at irection DRD B7 D D MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Library Routines Lcd Init Lcd Out Lcd Out Cp Lcd Chr Lcd Chr Cp Lcd Cmd Lcd Init CHAPTER 6 Libraries Initializes Lcd module Data bit 7 Data bit 6 Data bit 5 Data bit 4 Direction D6 Direction D5 Direction D4 Direction RS Direction EN Direction sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit module Lcd module connections dim LC LCD E LC 1 LC LG LED 1 dim Le LCD E LC LC LC LC End Lcd Init Register Select data instruction signal pin Enable signal pin Global variables LC i LC i LC i LC i LE i i i LCD EN i i Requires LC Da ion Di i LC Di ion Di i LC Di ion Di i LC Di ion Di i LCD RS Di ion Di i LCD_EN Di ion Di i must be defined before using this function Direction of the Data 7 pin Direction of the Data 6 pin Direction of the Data 5 pin Direction of the Data 4
77. 55 CHAPTER 2 Environment mikroBasic PRO for AVR UDP Terminal The mikroBasic PRO for AVR includes the UDP Terminal You can launch it from the drop down menu Tools UDP Terminal Settings IP Address 192 168 20 25 Pott 10001 Send mikroElektronika Send Append CR Send as typing EF Send as number mikroE lektronika Receive ASCII HEX DEC 56 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Graphic Lcd Bitmap Editor The mikroBasic PRO for AVR includes the Graphic Lcd Bitmap Editor Output is the mikroBasic PRO for AVR compatible code You can launch it from the drop down menu Tools Glcd Bitmap Editor 5 mikroElektronika Graphic LCD Bitmap generator T6363 Nokia3110 Ey ie FI File loaded truck bmp 2 T d Picture preview 128x64 pix bw lt 2 Load BMP Picture 077 Create CODE Invert PICTURE GLCD Size controller 7 7 GLCD Picture name truck bmp GLCD Model KS 1 8 128x64 const truck bmp array 18241 of byte 0 0 gt a WB se Wa 12 712 ales alas 12 18 18 1B 18 168 18 9 9 9 9 9 974 jg P E 9 022 792019 9 9 9 gt Ss 9 137 112 1317 137 137 137 137 137 127 127 1272127 1437 3 9 9 509 9 9 9 2 9 13 253 13 195 6 25
78. AGREEMENT MIKROELEKTRONIKA ASSOCIATES ENTIRE LIABILITY REGARDING SUPPORT SERVICES SHALL BE GOVERNED BY THE TERMS OF THAT AGREEMENT MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 5 CHAPTER 1 Introduction mikroBasic PRO for AVR HIGH RISK ACTIVITIES Software is not fault tolerant and is not designed manufactured or intended for use or resale as on line control equipment in hazardous environments requiring fail safe performance such as in the operation of nuclear facilities aircraft navigation or communication systems air traffic control direct life support machines or weapons systems in which the failure of Software could lead directly to death personal injury or severe physical or environmental damage High Risk Activities mikroElektron ika Associates and its suppliers specifically disclaim any expressed or implied war ranty of fitness for High Risk Activities GENERAL PROVISIONS This statement may only be modified in writing signed by you and an authorised offi cer of mikroElektronika Associates If any provision of this statement is found void or unenforceable the remainder will remain valid and enforceable according to its terms If any remedy provided is determined to have failed for its essential purpose all limitations of liability and exclusions of damages set forth in the Limited Warran ty shall remain in effect This statement gives you specific legal rights you may have others whi
79. AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Lcd Chr Prototvpe sub procedure Lcd Chr dim row as byte dim column as byte dim out char as byte Prints character on Lcd at specified position Both variables and literals can be passed as a character Parameters Description row Writing position row number column Writing position column number out char character to be written Requires The Lcd module needs to be initialized See Lcd Init routine Write character i at row 2 column 3 hed Ohr 2 3 var Lcd Chr Cp Prototype sub procedure Lcd Chr Cp dim out char as byte Nothing Prints character on Lcd at current cursor position Both variables and literals can be passed as a character Description Parameters out char character to be written Requires The Lcd module needs to be initialized See Lcd Init routine Example Write character e at current cursor position Lcd Chr Cp e MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 243 CHAPTER 6 Libraries mikroBasic PRO for AVR Lcd Cmd Prototype sub procedure Lcd Cmd dim out char as byte Sends command to Lcd Parameters Description out char command to be sent Note Predefined constants can be passed to the function see Available SPI Lcd Commands The Lcd module needs to be initialized See Lcd Init table Clear Lcd display Lcd Cmd LCD CLEAR
80. CF A1 CF 0 CF RDY CF WE direction CF direction as as as as as as as as sbit sbit sbit sbit sbit sbit sbit sbit at PI B 57 at PORTB B6 at PORI at PINB B4 B B5 at PORTB B3 at POR at PORT at PORT direction as as as CF CD1 direction as CF CEI direction as CF A2 direction CF 1 direction CF A0 direction as as as of cf pinout sbit sbit sbit sbit sbit sbit sbit sbit FAT TXT as string 20 file contents as string 50 filename as string 14 character as byte loop loop2 as byte size as longint Buffer as byte 512 dim i as byte Writes string to USART sub procedure Write Str dim byref ostr as byte 2 B B2 PB Bil 0 at at at at at at at at Ig E ded ES DRB DRB DRB DRB DRB B7 B6 B5 4 B3 DRB DRB DRB B2 BO File names MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 205 CHAPTER 6 Libraries mikroBasic PRO for AVR 0 while ostr i lt gt 0 UART1 i ine 2 wend UART1_ Write 0 end sub esce ues DIES Creates new file and writes some data to it sub procedure Create New File filename 7 A Cf Fat Assign filename 0 0 Will not find file and then create file Cf Fat Rewrite clear file and start with new data for loop 1 to 90 We want 5 files on t
81. CHAPTER 6 Libraries mikroBasic PRO for AVR HW Connection Pin diagram of MMC memory card 280 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries ONEWIRE LIBRARY The OneWire library provides routines for communication via the Dallas OneWire protocol e g with D818x20 digital thermometer OneWire is a Master Slave proto col and all communication cabling required is a single wire OneWire enabled devices should have open collector drivers with single pull up resistor on the shared data line Slave devices on the OneWire bus can even get their power supply from data line For detailed schematic see device datasheet Some basic characteristics of this protocol are single master system low cost low transfer rates up to 16 kbps fairly long distances up to 300 meters small data transfer packages Each OneWire device has also a unique 64 bit registration number 8 bit device type 48 bit serial number and 8 bit CRC so multiple slaves can co exist on the same bus Note Oscillator frequency Fosc needs to be at least 8MHz in order to use the rou tines with Dallas digital thermometers External dependencies of OneWire Library This variable must be defined in any project T that is using OneWire Description Library dim OW Bit Read as OneWire read line dim OW Bit Read as sbit sfr external j sbit at PINB B2 dim OW Bit Write as OneWir
82. Clock KHz Returns Device clock in KHz rounded to the nearest integer Function returns device clock in KHz rounded to the nearest integer Description This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit fe Clock MHz Returns Device clock in MHz rounded to the nearest integer Function returns device clock in MHz rounded to the nearest integer Description This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit 00000000 O O MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 99 CHAPTER 3 Specifics mikroBasic PRO for AVR SetFuncCall Prototype sub procedure SetFuncCall FuncName as string Function informs the linker about a specific routine being called SetFuncCall has to be called in a routine which accesses another routine via a pointer Description Function prepares the caller tree and informs linker about the procedure usage making it possible to link the called routine sub procedure first p q as byte SetFuncCall second let linker know that we will call the routine second end sub 100 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroBasic PRO for AVR Specifics CODE OPTIMIZATION Optimizer has been added to extend the compiler usability cut down the
83. D6 as sbit at D D7 as sbit at sbit sbit sbit sbit sbit sbit End Lcd module connections PORTD B2 DBS D B4 DBS PD B6 PD BY at at at at at at anchester module connections dim MANRXPIN as sbit at PINB BO MANRXPIN Direction as sbit at DDRB BO MANTXPIN as sbit at PORTB B1 MANTXPIN Direction as sbit at DDRB Bl dim error ErrorCount main ErrorCount 0 Delay 10us Led Tariy Lcd Cmd LCD CLEAR Man Receive Init while TRUE DDRD B2 DDRD B3 DDRD B4 DDRD B5 DDRD B6 DDRD B7 End Manchester module connections temp as byte Lcd Cmd LCD FIRST ROW Initialize Lcd Clear Lcd display Initialize Receiver Endless loop Move cursor to the lst row while TRUE Wait for the start byte temp Man Recervelterror Attempt byte receive if temp 0 0 then Start byte see Transmitter example break We got the starting sequence end if if error lt gt 0 then Exit so we do not loop forever break end if wend 252 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR while temp lt gt 0 0 temp Man Receive error if error lt gt 0 then Log Chr Inc ErrorCournt if CHAPTER 6 Libraries Attempt byte receive If error occured Write question mark on Lcd Update error counter Y ErrorCount 20 then In case of multiple errors temp Man Synchr
84. EXEML C TES 6 0 4 Device internal use only never found on disk Note Long File Names LFN are not supported MMC SD card and MMC library must be initialized for file operations See Requires 4 Fat Init Try to create a swap file with archive atribute whose size will be at least 1000 sectors If it succeeds it sends No of start sector over UART dim size as longword main Size Mmc Fat Get Swap File 1000 mikroE txt 0x20 if size then UART1 Write OxAA UART1 Write Lo size UART1 Write Hi size UART1 Write Higher size UART1 Write Highest size UART1 Write OxAA end if 272 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example The following example demonstrates MMC library test Upon flashing insert a MMC SD card into the module when you should receive the Init OK message Then you can experiment with MMC read and write functions and observe the results through the Usart Terminal if defined we have a debug messages on PC terminal program MMC Test SDEFINE RS232 debug dim MMC chip select as sbit at PORTB B2 dim MMC chip select direction as sbit at DDRB B2 universal variables dim i as word universal for loops and other stuff Variables for MMC routines dData as byte 512 Buffer for MMC sector reading writing da
85. FLASH Read Word 522 eR REA ERE EAR RA 215 FLASH Read Words 216 Library Example bean vr el pP e 216 Graphic Led Library sesgada akan ees 218 External dependencies of Graphic Lcd Library 218 Library Routines 219 Gled Ip one Dre e RU p C RO 220 Gled Set Side exe e 221 Glcd Set c 221 Set Page 222 Read _ 222 XIV MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Table of Contents 223 Glod dee ti ede hee da aed da 223 Gled DO 224 A ee Rx eg ER ER 224 Gled VV Line utt o medi eee gales 225 Gled ALLING beber Rer ore etre brew abd dias 225 Gled RectangGle scsi peta dees bee Sead EI UR RUN OR 226 Gled seans dree ie x REN Sha a ah Shae eae OR 227 Cleo qr 227 Gled Set Font ae oce eben grec CER ORR 228 229 Write Text 230 Glod Mago 252 244 ee tile bad toda d 230 Libr
86. FOR EMBEDDED WORLD 493 CHAPTER 6 Libraries strspn Prototype Description strstr Prototype Description mikroBasic PRO for AVR sub function strspn dim byref 51 52 as string 100 as byte The function searches the string s1 for characters not found in the s2 string The function returns the index of first character located si that does not match a character in s2 If the first character in si does not match a character in s2 a value of 0 is returned If all characters in s1 are found in s2 the length of 51 is returned not including the terminating null character sub function strstr dim byref sl 52 as stringi 100 as word The function locates the first occurrence of the string 52 in the string s1 exclud ing the terminating null character The function returns a number indicating the position of the first occurrence of s2 in s1 if no string was found the function returns oxrrrr If s2 is a null string the function returns O 494 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries TIME LIBRARY The Time Library contains functions and type definitions for time calculations in the UNIX time for mat which counts the number of seconds since the epoch This is very convenient for programs that work with time intervals the difference between two UNIX time values is a real time differ ence measured in seconds What is the epoch Ori
87. Flags initialize exter nal CANSPI module initialize 176 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR CANSPISetBaudRate CHAPTER 6 Libraries sub procedure CANSPISetBaudRate dim SJW as byte dim BRP as byte dim 5 as byte dim 5 2 as byte dim PROPSEG as byte dim CAN CONFIG FLAGS as byte Sets the CANSPI module baud rate Due to complexity of the CAN protocol you can not simply force a bps value Instead use this sub function when the CANSPI module is in Config mode SAM S Refer to datasheet for details Description Parameters sjw as defined in CAN controller s datasheet as defined in CAN controller s datasheet PHSEG PHSEG PBOPSI 1 as defined in CAN controller s datasheet 2 as defined in CAN controller s datasheet EG as defined CAN controller s datasheet EG2PHTS WAKFIL bits are set according to CAN CONFIG FLAGS value CAN CONFIG FLAGS 18 formed from predefined constants see CANSPI constants The CANSPI module must be in Config mode otherwise the sub function will be ignored See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page set required baud rate and sampling rules dim can config fla
88. GLeg 111 0 394 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI Glcd Dot sub procedure SPI Glcd Dot dim x pos as byte dim y pos as byte dim color as byte Prototype Draws a dot on Glcd at coordinates x pos v pos Parameters x pos X position Valid values 0 127 y pos y position Valid values 0 63 Description color COlx pos as byte page num as byte color as byte or parameter Valid values 0 2 The parameter color determines the dot state 0 clears dot 1 puts a dot and 2 inverts dot state Note For x and y axis layout explanation see schematic at the bottom of this page Requires Glcd needs to Glcd needs to be initialized for SPI communication see SPI Glcd Init routines initialized for SPI communication see SPI Glcd Init routines Invert RDUM SEO IIR t in upper left corner SPI Gled Dot SPI Glcd Line sub procedure SPI Glcd Line dim x start as integer dim y start as integer dim x end as integer dim y end as integer dim color as byte Draws a line on Glcd Parameters x start X coordinate of the line start Valid values 0 127 Description start y coordinate of the line start Valid values 0 63 x end X coordinate of the line end Valid values 0 127 y end y coordinate of the line end Valid values 0 63 color COlor parameter Valid values 0 2 Parameter color
89. HARDWARE SOLUTIONS FOR EMBEDDED WORLD 173 CHAPTER 6 Libraries mikroBasic PRO for AVR CANSPISetOperationMode sub procedure CANSPISetOperationMode dim mode as byte dim WAIT Prototype as Description Nothing Sets the CANSPI module to requested mode Parameters node CANSPI module operation mode Valid values 5 _ _ MODE con stants see CANSPI constants WAIT CANSPI mode switching verification request If wart 0 the call is non blocking The sub function does not verify if the CANSPI module is switched to requested mode not Caller must use CANSPIGetOperat ionMode to verify correct operation mode before performing mode specific operation If warr the call is blocking the sub function won t return until the requested mode is set The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page set the CANSPI module into configuration mode wait inside CANSPISetOperationMode until this mode is set CANSPISetOperationMode CANSPI MODE CONFIG OxFF CANSPIGetOperationMode Prototype sub function CANSPIGetOperationMode as byte Returns Current operation mode Description The sub function returns current operation mode of the CANSPI module Check CANSPI OP MODE constants see CANSPI constants or d
90. Library Functions iis beer Re REED a eee dns 489 mech Ded eda woe med ems 489 PEUT c rM E 490 us reed ata anit 490 MEMMOVE usc ases lM rues ae ewe s 490 491 SCIU PEPERIT 491 bees 491 dee mantenida pcc 491 RG 492 Cc 492 strlen 2 084 pius 492 Qu m 492 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XXV Table of Contents mikroBasic PRO for AVR ge Pc 493 493 Cg cc 493 SUCI e ens ME LUE 493 SSDM a quedes ima 494 SUSU i a hed Maw diues ideae ibi es 494 Time LIDrary a i er ren 495 Library RoutineS 495 Time dateToEpoch 495 Time epochToDate 496 496 Library eR Ree heh RR n 497
91. MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example The example demonstrates Software Library routines usage The AVR MCU is connected SCL SDA pins to PCF8583 RTC real time clock Program reads date and time are read from the RTC and prints it on Lcd program RTC Read dim seconds minutes hours day month year as byte Global date time variables Software I2C connections dim Soft I2C Scl Output as sbit at PORTC BO Soft I2C Sda Output as sbit at PORTC Bl SOLE I20 Sol Input as sbit at PINC BO Soft I2C Sda Input as sbit at Soft I2C Scl Direction as sbit at DDRC BO Soft I2C Sda Direction as sbit at DDRC Bl End Software I2C connections Lcd module connections dim LCD RS as sbit at PORTD B2 LCD EN as sbit at PORTD B3 LCD D4 as sbit at PORTD B4 LCD DS as sbit at PORTD B5 LCD D6 as sbit at PORTD B6 LCD D7 as sbit at PORTD B7 LCD RS Direction as sbit at DDRD B2 LCD EN Direction as sbit at DDRD B3 LCD D4 Direction as sbit at DDRD B4 LCD D5 Direction as sbit at DDRD B5 LCD D6 Direction as sbit at DDRD B6 LCD D7 Direction as sbit at DDRD B7 End Lcd module connections Reads time and date information from RTC PCF8583 sub procedure Read Time Sort Start Issue start signal Soft I2C Write 0xA0 Address PCF8583 see PCF8583 datasheet SOLL Werte 2 Start f
92. Quick Help Check For Updates Check if new compiler version is available mikroElektronika Support Forums Open mikroElektronika Support Forums in a default browser mikroElektronika Web Page Open mikroElektronika Web Page in a default browser Information on how to register 22 How To Register Open About window Related topics Keyboard shortcuts 28 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment KEYBOARD SHORTCUTS Below is a complete list of keyboard shortcuts available in mikroBasic PRO for AVR IDE You can also view keyboard shortcuts in the Code Explorer window tab Keyboard Esas n i i MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 29 9 9 x x Ctrl N Ctrl Shift O Ctri K Ctrl F9 Shift F9 Ctrl F 11 Shift F4 orererererererere i I 42 3 3 O Sj 5 CHAPTER 2 Environment mikroBasic PRO for AVR Software Simulator Shortcuts 30 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR IDE OVERVIEW CHAPTER 2 Environment The mikroBasic PRO for AVR is an user friendly and intuitive environment E e warme Message No Message Test m 1 RANE LEG PATMEGAG MSF Y D OLII Complation Stated Compad Sccessfuly Ab
93. Spi Ethernet UNICAST enable CRC checking and Unicast traffic Spi Ethernet Disable Prototype Description sub procedure Spi Ethernet Disable dim disFlt as byte Nothing This is MAC module routine This routine disables appropriate network traffic on the ENC28J60 module by the means of it s receive filters unicast multicast broadcast crc Specific type of network traffic will be disabled if a correspon ding bit of this routine s input parameter is set Therefore more than one type of network traffic can be disabled at the same time For this purpose predefined library constants see the table below can be ORed to form appropriate input value Parameters disFit network traffic receive filter flags Each bit corresponds to the appropriate network traffic receive filter 372 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries MAC Broadcast traffic receive filter 0x01 flag When set MAC broadcast traffic Spi Ethernet BROADCAST will be disabled MAC Multicast traffic receive filter i 0 02 flag When set MAC multicast traffic 5 Ethernet MULTICAST will be disabled Description CRC check flag When set CRC check 0x20 will be disabled and packets with invalid 55i Ethernet CRC field will be accepted pe MAC Unicast traffic receive filter flag 7 0x80 W
94. TX Idle Ptr UART1 Init 9600 Delay ms 100 RS485Slave Init 160 CHAPTER 6 Libraries Pass pointers to UART sub functions of used UART module QUARTI Write UART1 Read UART1 Data Ready UART1 TX Idle initialize UART1 module Y Intialize MCU as slave address 160 dat 4 0 ensure that message received flag is 0 dat 5 0 ensure that message received flag is 0 dat 6 0 ensure that error flag is 0 SREG I bit 1 enable global interrupt RXCIE bit I enable interrupt on UARTs receive while TRUE if dat 5 lt gt 0 then if an error detected signal it by PORTC dati 5 5 setting PORTC dat 5 0 end if if dat 4 lt gt 0 then upon completed valid message receiv dat 4 0 data 4 is set to OxFF dat 3 for i 1 to dat 3 show data on PORTB PORTB dat 1 1 next i dat 0 0 1 increment received dat 0 Delay ms 1 548551 Send dat 1 and send it back to master end if wend end MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 335 CHAPTER 6 Libraries mikroBasic PRO for AVR HW Connection Shielded pair no longer than 300m Example of interfacing PC to ATmega16 MCU via RS485 bus with LTC485 as RS 485 transceiver 336 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Message format and CRC calculations How is CRC checksum calculated on R
95. This function compares two dates and returns time difference in seconds as a signed long The result is positive if c1 is before 2 null if 1 is the same as t2 and negative if 1 is after t2 Prototype Description Parameters t1 time and date structure the first comparison parameter t2 time and date structure the second comparison parameter dim tsl ts2 as TimeStruct diff as longint how many seconds between these two dates contained in tsl and ts2 buffers diff Time dateDsfr tsl t52 496 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example Demonstration of Time library routines usage for time calculations in UNIX time format program Time Demo dim epoch diff as longint ckck ck ck ck ck kk ck ck ck ckck ckckck tsl ts2 as TimeStruct LE E oX xo X o d d E M d ck E E E EE f d E E o EE m E E E E E aro fe Es main tsliss 0 tsl mn 7 tsl hh 17 tsl md 23 tsl mo 5 tsl yy 2006 What is the epoch of the date in ts epoch Time dateToEpoch ts1 1148404020 What date is epoch 1234567890 epoch 1234567890 Time epochToDate epoch ts2 1 OxlE 0x17 Ox0D 0x04 0x02 0 07 9 How much seconds between this two dates diff Time dateDiff G0tsl 6 82 86163870 end TimeStruct type definition structure TimeStruct di
96. TimeStruct type definition 497 Trigonometry Library 498 Library Routines 498 498 COSE inh P ETT 499 XXVI MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER Introduction to mikroBasic PRO for AVR The mikroBasic PRO for AVR is a powerful feature rich development tool for AVR microcontrollers It is designed to provide the programmer with the easiest possi ble solution to developing applications for embedded systems without compromis ing performance or control CHAPTER 1 Introduction mikroBasic PRO for AVR 4317312323523 14 lt mikroBasic PRO for AVR IDE Features mikroBasic PRO for AVR allows you to quickly develop and deploy complex applications Write your Basic source code using the built in Code Editor Code and Parameter Assistants Code Folding Syntax Highlighting Spell Checker Auto Correct Code Templates and more Use included mikroBasic PRO libraries to dramatically speed up the development data acquisition memory displays conversions communication etc Monitor your program structure variables and functions in the Code Explorer Generate commented human readable assembly and standard HEX compatible with all programmers Inspect program flow and debug e
97. WORLD 45 CHAPTER 2 Environment mikroBasic PRO for AVR ERROR WINDOW In case that errors were encountered during compiling the compiler will report them and won t generate a hex file The Error Window will be prompted at the bottom of the main window by default The Error Window is located under message tab and displays location and type of errors the compiler has encountered The compiler also reports warnings but these do not affect the output only errors can interefere with the generation of hex Messages Errors v Warnings v Hints Line Message No Message Text Unit 0 1 mBAVR exe DBG pATMEGA16 MSF Y DL 0 132 Compilation Started C PROGRAM FILES MIKROELEKTRONIKA MIKROBASIC PRO FOR AVRYEXAMPLESYOTHERYSOUNDI 42 303 Identifier Tone2 was not declared Sound mbas 42 304 Syntax error Expected end but Tone2 found Sound mbas 42 304 Syntax error Expected sub but found Sound mbas 42 304 Syntax error Expected end but Found Sound mbas 42 304 Syntax error Expected but Tone3 Found Sound mbas 0 102 Finished with errors 29 Nov 2008 09 23 26 Sound mbpav Double click the message line in the Error Window to highlight the line where the error was encountered Related topics Error Messages 46 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment STATISTICS After successful compilation you can rev
98. Within a list the character is used to specify a range so that a z represents all characters between a and z inclusive If you want itself to be a member of a class put it at the start or end of the list or precede it with a backslash If you want you may place it at the start of list or precede it with a backslash Examples az matches z and az matches z a z matches z a z matches all twenty six small characters from a to z n x0D matches any of 10 11 12 13 d t matches any digit or c 1 matches any char from Metacharacters Metacharacters are special characters which are the essence of regular expres sions There are different types of metacharacters described below Metacharacters Line separators start of line end of line Start of text z end of text any character in line MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 63 CHAPTER 2 Environment mikroBasic PRO for AVR Examples PORTA matches string PORTA only if it s at the beginning of line PORTAS matches string PoRTA only if it s at the end of line PORTAS matches string PORTA only if it s the only string in line PORT r matches strings like PORTA PORTB PORT1 and so The metacharacter by default is only guaranteed to match beginning of the input st
99. Write Text Write Error end if UART1 Write 13 UART1 Write 10 SENDIF Reading of CID CSD register on MMC card SIFDEF RS232 debug i Mmc Read Cid data for registers if i 0 then for k 0 to 15 printhex data for registers if k lt gt 15 then UART1 Write 274 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries end if next k VARTI Write 13 else U ARTI Write Text CID error end if i Read Csd data for registers if i 0 then for k 0 to 15 printhex data for registers k if k lt gt 15 then UART1 Write end if next K UART1 Write 13 UART1 Write 10 else UART1 Write Text CSD error end if SENDIF end Following example consists of several blocks that demonstrate various aspects of usage of the Mmc_Fat16 library These are Creation of new file and writing down to it Opening existing file and re writing it writing from start of file Opening existing file and appending data to it writing from end of file Opening a file and reading data from it sending it to USART terminal Creating and modifying several files at once Program MMC FAT Test dim Mme Chip Select as sbit at PORTG B1 Mme Chip Select Direction as sbit at DDRG B1 dim FAT TXT as string 20 file contents as string 50 filename as string 14 File names character as byte loop loop2 as by
100. a part of the program in which the identifier can be used to access its object There are different categories of scope depending on how and where identifiers are declared Scope extends from the point where it is declared to the end of the current file including all routines enclosed within that scope These identifiers have a file scope and are referred to as globals Identifier is declared in the declaration section of the main module out of any function or procedure Scope extends from the point where it is declared to the end of the current routine These identifiers are referred to as locals Identifier is declared in the function or procedure Scope extends the interface section of a module from the point where it is declared to the end of Identifier is declared in the the module and to any other module or program interface section of the module that uses that module The only exception are symbols which have a scope limited to the file in which they are declared Identifier is declared in the Scope extends from the point where it is implementation section of the declared to the end of the module The identifier module but not within any is available to any function or procedure in the function or procedure module Visibility The visibility of an identifier is a region of the program source code from where a legal access to the identifier s associated object can be made Scope and visibility usually coincide tho
101. active editor Eind Ctrl F Find text in active editor Find Next F3 Find next occurence of text in active editor Find Previous Shift F3 Find previous occurence of text in active editor Replace Ctri R Replace text in active editor 7 Find text in current file in all opened files or in files Find In AIFS ffrom desired folder Goto Line Ctrl G Goto to the desired line in active editor Advanced Advanced Code Editor options MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 15 CHAPTER 2 Environment mikroBasic PRO for AVR File Description Comment selected code or put single line com ment if there is no selection Uncomment selected code or remove single line comment if there is no selection Comment Shift Ctrl4 Uncomment Shift Ctrl Indent Shift Ctrl I Indent selected code 5 Outdent Shift Ctr LJ Outdent selected code Aal Lowercase Ctrl Alt L Changes selected text case to lowercase aA Uppercase Ctrl A4lt U Changes selected text case to uppercase Titlecase Ctrl 4lt T Changes selected text case to titlercase Find Text Dialog box for searching the document for the specified text The search is per formed in the direction specified If the string is not found a message is displayed Find Text Search for Options Case sensitivity Directi
102. address 0x100 counter next counter EEPROM Write 0x02 0xAA Write some data at address 2 EEPROM Write 0x150 0x55 Write some data at address 0x150 Delay ms 1000 Blink PORTA and PORTB diodes PORTA OxFF to indicate reading start PORTB OxFF Delay 1000 0 00 PORTB 0x00 Delay ms 1000 PORTA EEPROM Read 0x02 Read data from address 2 and display it on PORTA PORTB EEPROM Read 0x150 Read data from address 0x150 and display it on PORTB Delay ms 1000 for counter 0 to 31 Read 32 bytes block from address 0x100 PORTC EEPROM Read 0x100 counter and display data on PORTC Delay ms 100 next counter end MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 213 CHAPTER 6 Libraries mikroBasic PRO for AVR FLASH MEMORY LIBRARY This library provides routines for accessing microcontroller Flash memory Note that prototypes differ for MCU to MCU due to the amount of Flash memory Note Due to the AVR family flash specifics flash library is MCU dependent Since some AVR MCU s have more or less than 64kb of Flash memory prototypes may be different from chip to chip Please refer to datasheet before using flash library Note Currently Write operations are not supported See mikroBasic PRO for AVR specifics for details Library Routines FLASH Read Byte FLASH Read Bytes FLASH Read Word FLASH Read Words FLASH Read Byte
103. as type functions prototypes sub function sub function name dim byref const ParamName type dim byref const ParamName2 ParamName3 as type as type Ck kk ck ko kk Implementation Vk ckCkck ck ck ck ck ck ck k ck ck ck k ck ck ck k ck ck kk ck ck kk ck ck ck k ck ck ck k ck ck ck ck ck ck kk ck ck ck k ck k k k kk kk implements constants declarations const variables declarations dim MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 121 CHAPTER 5 Language Reference mikroBasic PRO for AVR procedures declarations sub procedure sub procedure name dim byref const ParamName as type dim byref const ParamName2 ParamName3 type ilevel 0x123 overload forward local declarations end sub functions declarations sub function sub function name dim byref const ParamName as type dim byref const ParamName2 ParamName3 as type as type ilevel 0x123 overload forward local declarations end sub end Note Sub functions and sub procedures must have the same declarations in the interface and implementation section Otherwise compiler will report an error 122 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference SCOPE AND VISIBILITY Scope The scope of identifier is
104. at PORTD B2 LCD EN as sbit at PORTD B3 LCD D4 sbit at PORTD B4 LCD D5 as sbit at PORTD B5 LCD D6 as sbit at PORTD B6 LCD D7 as sbit at PORTD B7 LCD RS Direction as sbit at DDRD B2 LCD EN Direction as sbit at DDRD B3 LCD D4 Direction as sbit at DDRD B4 LCD D5 Direction as sbit at DDRD B5 LCD D6 Direction as sbit at DDRD B6 LCD D7 Direction as sbit at DDRD B7 End Lcd module connections OneWire pinout dim OW Bit Write as sbit at PORTB B2 OW Bit Read as sbit at PINB B2 OW Bit Direction as sbit at DDRB B2 end OneWire definition Set TEMP RESOLUTION to the corresponding resolution of used DS18x20 sensor 1 1852049 default setting be 9 10 11 or 12 t 18B20 12 const TEMP RESOLUTION as byte 12 dim text as 9 temp as word sub procedure Display Temperature dim temp2write as word const RES SHIFT TEMP RESOLUTION 8 dim temp whole as byte temp fraction as word text 000 0000 check if temperature is negativ if temp2write and 0x8000 then text 0 temp2write not temp2write 1 end if MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 285 CHAPTER 6 Libraries mikroBasic PRO for AVR extract temp whole temp whole word temp2write RES SHIFT r convert temp whole to characters if temp whole div 100 then text 0 temp whole div 100 48 else 0 0 end if text 1 temp whole div 10 mod 1
105. be initialized See SPI T6963C Config routine 5 T6963C WriteCommand SPI T6963C CURSOR POINTE SPI T6963C SetPtr Prototype sub procedure SPI T6963C SetPtr dim p as word dim c as byte Sets the memory pointer p for command c Description Parameters p address where command should be written c command to be written Requires SToshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C SetPtr T6963C grHomeAddr start T6963C ADDRESS POINTER SET SPI T6963C WaitReady Prototype sub procedure SPI T6963C WaitReady Pools the status byte and loops until Toshiba Glcd module is ready Toshiba Glcd module needs to be initialized See SPI T6963C Config routine ee 424 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI T6963C Fill sub procedure SPI T6963C Fill dim v as byte dim start as word Prototype dim len as word Fills controller memory block with given byte Parameters Description v byte to be written start Starting address of the memory block 1en length of the memory block in bytes Toshiba Glcd module needs to be initialized See SPI 6963 Config routine Example SPI T6963C Fill 0x33 0 00 0x000F SPI T6963C Dot sub procedure SPI T6963C Dot dim x as integer dim y as integer Prototype dim color as byte Draws a dot in the cu
106. byte dim color as byte Draws a vertical line on Glcd Parameters y start y coordinate of the line start Valid values 0 63 Description end y coordinate of the line end Valid values 0 63 x pos X Coordinate of vertical line Valid values 0 127 color COlor parameter Valid values 0 2 The parameter color determines the line color 0 white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd Init routine Draw a vertical line between dots 10 5 and 10 25 Gled V Line 5 25 10 1 Glcd H Line sub procedure Glcd V Line dim x start as byte dim x end as byte Prototype dim y pos as byte dim color as byte Draws a horizontal line on Glcd Parameters x start X coordinate of the line start Valid values 0 127 Description x end x coordinate of the line end Valid values 0 127 y pos y coordinate of horizontal line Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the line color 0 white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd Init routine Draw a horizontal line between dots 10 20 and 50 20 Glcd Line 10 50 20 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 225 CHAPTER 6 Libraries mikroBasic PRO for AVR Glcd Rectangle sub procedure Glcd Rectangle dim x upper left as byte dim y upper left as byte dim x bottom right as byte di
107. declaring a variable data specifier will be set as default by the compiler Related topics AVR Memory Organization Accessing individual bits SFRs Constants Functions MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER mikroBasic PRO for AVR Language Reference The mikroBasic PRO for AVR Language Reference describes the syntax semantics and implementation of the mikroBasic PRO for AVR language The aim of this reference guide is to provide a more understandable description of the mikroBasic PRO for AVR language to the user 109 CHAPTER 5 Language Reference mikroBasic PRO for AVR MIKROBASIC PRO FOR AVR LANGUAGE REFERENCE Lexical Elements Whitespace Comments Tokens Literals Keywords Identifiers Punctuators Program Organization Program Organization Scope and Visibility Modules Variables Constants Labels Symbols Functions and Procedures Functions Procedures Types Simple Types Arrays Strings Pointers Structures Types Conversions Implicit Conversion Explicit Conversion Operators Introduction to Operators Operators Precedence and Associativity Arithmetic Operators Relational Operators Bitwise Operators Boolean Operators Expressions Expressions Statements Introduction to Statements Assignment Statements Conditional Statements 110 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference If Statement
108. drivers For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Note The library uses the SPI module for communication The user must initialize SPI module before using the SPI T6963C Library Note This Library is designed to work with mikroElektronika s Serial Glcd 240x128 and 240x64 Adapter Boards pinout see schematic at the bottom of this page for details Note Some mikroElektronika s adapter boards have pinout different from T6369C datasheets Appropriate relations between these labels are given in the table below Adapter Board T6369C datasheet External dependencies of SPI T6963C Graphic Lcd Library The implementation of SPI T6963C Graphic Lcd Library routines is based on Port Expander Library routines Prior to calling any of this library routines Spi Rd Ptr needs to be initialized with the appropriate SPI Read routine External dependencies are the same as Port Expander Library external dependencies 420 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Library Routines SPI T6963C Config SPI T6963C WriteData SPI T6963C WriteCommand SPI T6963C SetPtr SPI T6963C WaitReady SPI T6963C Fill SPI T6963C Dot SPI T6963C Write Char SPI T6963C Write Text SPI T6963C Line SPI T6963C Rectangle SPI T6963C Box SPI T6963C Circle SPI T6963C Image SPI T6963C Sprite SPI T6963C Set Cursor
109. e PORTA 4 is pressed change cursor else if PINA4 bit 0 then ne eurs if curs curs 0 end if select case curs case 0 no curser T6963C cursor 0 case 1 blinking curser T6963C0 Cursor 1 T6963C cursor blink 1 case 2 non blinking curser T6963C cursor 1 T6963C cursor blink 0 end select Delay ms 300 3 then end if end if end if end if end if 462 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Move cursor even if not visible Inc cposx if cposx T6963C txtCols then cposx 0 Ine cposy if cposy cposy 0 end if end if T6963C set cursor cposx cposy T6963C_grHeight T6963C_CHARACTER_HEIGHT then Delay ms 100 wend end MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 463 CHAPTER 6 Libraries mikroBasic PRO for AVR HW Connection OSCILLATOR gt O o Toshiba T6963C Graphic LCD 240x128 38 3823233332333 4 RoMWOULroWuoonao vcc VCC C Contrast Adjustment T6963C Glcd HW connection 464 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroBasic PRO for AVR Introduction TWI LIBRARY TWI full master MSSP module is available with a number of AVR MCU models mikroBasic PRO for AVR provides library which supports the master TWI mode Library Routines TWI I
110. end 350 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SOFTWARE UART LIBRARY The mikroBasic PRO for AVR provides routines for implementing Software UART communication These routines are hardware independent and can be used with any MCU The Software UART Library provides easy communication with other devices via the RS232 protocol Note The Software UART library implements time based activities so interrupts need to be disabled when using it External dependencies of Software UART Library The following variables must be defined in all Description projects using Software UART Library dim Soft UART Rx Pin Receive line dim Soft UART Rx Pin as sbit sfr external as sbit at PIND BO dim Soft UART Tx Pin Transmit line dim Soft VART Tx Pin as sbit sfr external as sbit at PORTD B1 dim dim Soft UART Rx Pin Dire Direction of the Receive Soft UART Rx Pin Dire ction as sbit sfr in ction as sbit at external DDRD BO dim dim Soft UART Tx Pin Dire Direction of the Transmit Soft_UART Tx Pin Dire ction as sbit sfr in ction as sbit at external DURD B4 Library Routines Soft UART Init Soft UART Read Soft UART Write Soft UART Break MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 351 CHAPTER 6 Libraries mikroBasic PRO for AVR Soft UART Init Prototype Description sub function Soft UART
111. flag and is still in force The directive 1FDEF is terminated by the NDIF directive and can have any num ber of the LSEIF clauses and an optional lt clause 164 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference IFDEF flag THEN block of code fELSEIF flag 1 THEN block of code 1 ELSEIF flag n THEN block of code n ELSE alternate block of code ENDIF First 4 irbEr checks if flag is set by means of DEFINE If so only block of code will be compiled Otherwise the compiler will check flags flag 1 flag n and exe cute the appropriate block of code i Eventually if none of the flags is set alternate block of code in LsE if any will be compiled ENDIF ends the conditional sequence The result of the preceding scenario is that only one section of code possibly empty is passed on for further processing The processed section can contain further conditional clauses nested to any depth each irper 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 SETE resolution10 THEN code specific to 10 bit resolution
112. fles Conpled in 63 me ced E bytes 17 S996 Free RX bytes 15 47 Sati RAM 46 Oyrar RAM bytes 978 ni ed ROM Project Project VCD nbpav completed 733 mi Fried successhuly 28 Nov 2008 19 58 28 Move text to the right 4 times Delay us des Tave Jn us asl Delay ms ond dm Jn s as LongWord SetFuncCall m Fanctonhisne Baud as OWor Used RX bytes 17 53 Free RX bytes 15 47 Dynami BAM bytes 978 Used ROM bytes 1712 1236 Free RCM bytes 12623 88 The Code Editor features adjustable Syntax Highlighting Code Folding Code Assistant Parameters Assistant Spell Checker Auto Correct for common typos and Code Templates Auto Complete The Code Explorer with Keyboard shortcut browser and Quick Help browser is at your disposal for easier project management The Project Manager alows multiple project management General project settings can be made in the Project Settings window Library manager enables simple handling libraries being used in a project The Error Window displays all errors detected during compiling and linking The source level Software Simulator lets you debug executable logic step by step by watching the program flow The New Project Wizard is a fast reliable and easy way to create a project Help files are syntax and context sensitive Like in any modern Windows application you ma
113. for AVR Libraries Library Example The example is a simple demonstration of how to use the Sound Library for playing tones on a piezo speaker program Sound Sound connections dim Sound Play Pin as sbit at PORTC B3 dim Sound Play Pin direction as sbit at DDRC B3 End Sound connections sub procedure 1 Sound Play 500 200 Frequency 500Hz Duration 200ms end sub sub procedure Tone2 Sound Play 555 200 Frequency 555Hz Duration 200ms end sub sub procedure Tone3 Sound Play 625 200 Frequency 625Hz Duration 200ms end sub sub procedure Melody Plays the melody Yellow house Tonel Tone2 Tone3 Tone3 Tonel Tone2 Tone3 Tone3 Tonel Tone2 Tone3 Tonel Tone2 Tone3 Tone3 Tonel Tone2 Tone3 Tone3 Tone3 Tone2 Tone2 Tonel end sub sub procedure ToneA Tones used in Melody2 function Sound Play 1250 20 end sub sub procedure ToneC Sound Play 1450 20 end sub sub procedure ToneE Sound Play 1650 80 end sub sub procedure Melody2 Plays Melody2 dim counter as byte for counter 9 to 1 step 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 359 CHAPTER 6 Libraries mikroBasic PRO for AVR ToneA ToneC ToneE next counter end sub main DDRB 0x00 Delay ms 2000 Sound Init Sound Play 2000 ond while TRUE if PINB 7 lt gt Tonel while nop wend end if PINB if P
114. form value to be used with CANSendMessage send config CANSPI TX PRIORITY 0 and CANSPI TX XTD FRAME and CANSPI TX NO RTR FRAME CANSPIIWrite id data 1 send config MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 183 CHAPTER 6 Libraries mikroBasic PRO for AVR CANSPI MSG FLAGS CANSPI RX MSG FLAGS are flags related to reception of CAN message If a par ticular bit is set then corresponding meaning is TRUE otherwise it will be FALSE const CANSPI RX FILTER BITS as byte 07 Use this to access filter bits CANSPI RX FILTER 1 as byte 00 CANSPI RX FILTER 2 as byte 01 CANSPI RX FILTER 3 as byte 02 CANSPI RX FILTER 4 as byte 03 CANSPI RX FILTER 5 as byte 04 CANSPI RX FILTER 6 as byte 05 CANSPI RX OVERFLOW as byte 08 Set if Overflowed else cleared CANSPI RX INVALID MSG as byte 10 Set if invalid else cleared CANSPI RX XTD FRAME as byte 520 Set if XTD mes sage else cleared CANSPI RX RTR FRAME as byte 40 Set if RIR meg sage else cleared CANSPI RX DBL BUFFERED as byte 80 Set if this mes sage was hardware double buffered You may use bitwise and to adjust the appropriate flags For example if MsgFlag and CANSPI RX OVERFLOW lt gt 0 then Receiver overflow has occurred We have lost our previous message end if CANSPI MASK The MASK constants define mask
115. image to be displayed Bitmap array must be located in code memory Use the mikroBasic PRO for AVR integrated Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd Glcd needs to be initialized see Glcd Init routine Draw image my image on Glcd Glcd Image my image 230 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example The following example demonstrates routines of the Glcd library initialization clear pattern fill image displaying drawing lines circles boxes and rectangles text displaying and handling program Glcd Test include bitmap Glcd module connections dim GLCD DataPort as byte at PORTC GLCD DataPort Direction as byte at DDRC dim GLCD CS1 as sbit at PORTD B2 LCD 52 sbit at PORTD B3 LCD RS sbit at PORTD B4 LCD RW as sbit at PORTD B5 CD as sbit at PORTD B6 LCD RST as sbit at PORTD B7 q m x mg dim GLCD CS1 Direction as sbit at DDRD B2 GLCD CS2 Direction as sbit at DDRD B3 GLCD RS Direction as sbit at DDRD B4 GLCD RW Direction as sbit at DDRD B5 GLCD EN Direction as sbit at DDRD B6 GLCD RST Direction as sbit at DDRD B7 End Glcd module connections dim counter as byte someText as char 18 sub procedure 1 25 f function Delay ms 2000 end sub 2 seconds delay sub main Gica Init Initialize Glcd Glcd Fill 0
116. include Lib SPIT6963C Const include bitmap include bitmap2 dim Port Expander module connections SPExpanderRST sbit at PORTB BO SPExpanderCS sbit at PORTB B1 SPExpanderRST Direction as sbit at DDRB BO SPExpanderCS Direction sbit at DDRB Bl End Port Expander module connections dim panel as byte current panel i as word general purpose register curs as byte Curser yisibility eposx as word cursor x y position txt txtl as stringi 29 txtl EINSTEIN WOULD HAVE LIKED mE txt GLCD LIBRARY DEMO WELCOME DDRA 0x00 configure PORTA as input init display for 240 pixel width and 128 pixel height t 8 bits character width data bus 23517 portB control bus on 23817 portA ok pit 2 15 IWR Y CP bro 2 xs IRD t pit 0 is ICD pit 4 15 BST chip enable reverse on 8x8 font internaly set in library Pass pointer to SPI Read function of used SPI module Spi Rd Ptr 65 1 Read Initialize SPI module 5 1 Init Advanced SPI MASTER SPI DIV2 SPI CLK HI TRAIL ING MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 437 CHAPTER 6 Libraries mikroBasic PRO for AVR Pass pointer to SPI Read function of Spi Rd Ptr 85 2 Read function of used SPI module Initialize SPI module used with Portl If Port Expander Library uses SPI2 module used SPI module
117. information refer to Labels Dot Dot indicates access to a structure member For example person surname Smith For more information refer to Structures Dot is a necessary part of floating point literals Also dot can be used for accessing individual bits of registers in mikroBasic PRO MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 119 CHAPTER 5 Language Reference mikroBasic PRO for AVR PROGRAM ORGANIZATION mikroBasic PRO for AVR imposes strict program organization Below you can find models for writing legible and organized source files For more information on file inclusion and scope refer to Modules and to Scope and Visibility Organization of Main Module Basically a main source file has two sections declaration and program body Dec larations should be in their proper place in the code organized in an orderly man ner Otherwise the compiler may not be able to comprehend the program correctly When writing code follow the model presented below The main module should look like this program program name include include other modules Vok ck ck Ck ck Ck Ck Ck ck ck Ck ck Ck Ck Sk Ck ck kk ck ko Sk kv Sk kv kc k ck Declarations globals PRG REOR PX ROGER WR REGN symbols declarations symbol constants declarations const structures declarations structure variables declarations dim Name Name2 as type absol
118. mikroBasic PRO for AVR SPI Glcd Box sub procedure SPI Glcd Box dim x upper left as byte dim y upper left as byte dim x bottom right as byte dim y bottom right as byte dim color as byte Draws a box on Glcd Parameters x upper left X coordinate of the upper left box corner Valid values 0 127 y upper left y coordinate of the upper left box corner Valid values 0 63 x bottom right X coordinate of the lower right box corner Valid values 0 127 y bottom right y coordinate of the lower right box corner Valid values 0 63 color color parameter Valid values 0 2 Description The parameter color determines the color of the box fill O white 1 black and 2 inverts each dot Glcd needs to be initialized for SPI communication see Glcd Init routines Draw a box between dots 5 15 and 20 40 SPI Gled Box 5 15 20 40 1 SPI Glcd Circle sub procedure SPI Glcd Circle dim x center as integer dim y cen ter as integer dim radius as integer dim color as byte Draws a circle on Glcd Parameters x center X coordinate of the circle center Valid values 0 127 Description y center y coordinate of the circle center Valid values 0 63 radius radius size color COlor parameter Valid values 0 2 The parameter color determines the color of the circle line 0 white 1 black and 2 inverts each dot Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init
119. mikroBasic PRO for AVR at the time of activation Notes The license key is valid until you format your hard disk In case you need to format the hard disk you should request a new activation key Please keep the activation program in a safe place Every time you upgrade the compiler you should start this program again in order to reactivate the license 10 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER mikroBasic PRO for AVR Environment The mikroBasic PRO for AVR is an user friendly and intuitive environment CHAPTER 2 Environment mikroBasic PRO for AVR IDE OVERVIEW news procedir Delay us dn Tre ju s nord a Daley ms dim 1n mes as LongWord ERN LOG PATMEGALG MSF V DL 011111114 Complaton Creed Al fles Congled n 63 ne Used bytes 17 59 Pree RX bytes 15 47 Used RX bytes 17 53 Free RX bytes 15 4796 Sta RAM bytes 46 Dynamic RAM bytes 970 Used ROM bytes 1712 12 Free ROM bytes 12623 58 ACD mbpav Project CD pav completed 733 ms Fristed successfuby 28 Nov 2008 15 55 28 od The Code Editor features adjustable Syntax Highlighting Code Folding Code Assistant Parameters Assistant Spell Checker Auto Correct for common typos and Code Templates Auto Complete The Code Explorer with Keyboard shortcut browser and Quick Help browser is at your disposal
120. mikroBasic PRO s integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for display ing on Glcd Toshiba Glcd module needs to be initialized See the T6963C Init routine oem O OS T6963C Sprite sub procedure T6963C Sprite dim px py sx sy as byte const pic s byte Fills graphic rectangle area px py to px sx py sy with custom size picture Prototype Parameters px X coordinate of the upper left picture corner Valid values multiples of the font width Description y coordinate of the upper left picture corner pic picture to be displayed sx picture width Valid values multiples of the font width sy picture height Note and sx parameters are not multiples of the font width they will be scaled to the nearest lower number that is a multiple of the font width Toshiba Glcd module needs to be initialized See the T6963C Init routine Example 76963 Sprite 76 4 einstein 88 119 draw a sprite MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 453 CHAPTER 6 Libraries mikroBasic PRO for AVR T6963C Set Cursor Prototype sub procedure 6963 Set Cursor dim x y as byte Sets cursor to row x and column y Description Parameters x cursor position row number y cursor position column number Toshiba Glcd module needs to be initialized See the T6963C_Init routine 730 T696
121. on every MCU Please use Code Assistant to see if this value is available for the given MCU Sets prescaler value to 64 Sets prescaler value to 128 this value is not available on every MCU Please use Code Assistant to see if this value is available for the given MCU 308 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Sets prescaler value to 1 on second PWM library if it exists in Library Manager Sets prescaler value to 8 on second PWM library if it exists in Library Manager Sets prescaler value to 32 on second PWM library if it exists in Library Manager This value is not available on every MCU Please use Code Assistant to see if this value is available for the given MCU PWM1 PRESCALER Sets prescaler value to 64 on second PWM library if it exists in Library Manager PWM1 PRESCALER Sets prescaler value to 128 on second PWM library if it exists in Library Manager This value is not available on every MCU Please use Code Assistant to see if this value is available for the given MCU Badupitas wee Sets prescaler value to 256 on second PWM library if it exists in Library Manager Sets prescaler value to 1024 on second PWM library if ni it exists in Library Manager Selects the inverted PWM mode
122. pin Direction of the Register Select pin Direction of the Enable signal pin at PORTD B2 at PORTD B3 at PORTD B4 PORTD B5 at PORTD B6 at PORTD B7 at DDRD B2 at DDRD B3 at DDRD B4 at DDRD B5 at DDRD B6 at DDRD B7 connections MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 241 CHAPTER 6 Libraries mikroBasic PRO for AVR Lcd Out Prototvpe sub procedure Lcd Out dim row as byte dim column as byte dim yp byref text as string 201 Prints text on Lcd starting from specified position Both string variables and liter als can be passed as a text Parameters Description row Starting position row number column Starting position column number text text to be written Requires The Lcd module needs to be initialized See Led module needs to be initialized See Lcd Initroutine routine Write text Hello on Lcd from row 1 column 3 Led QOut i 3 Lcd Out Cp Prototype sub procedure Lcd Out Cp dim byref text as stringi 191 Prints text on Lcd at current cursor position Both string variables and literals can be passed as a text Deseription Parameters text text to be written Requires The Lcd module needs to be initialized See Lcd Init routine Write text Here at current cursor position Led Out Cp Here 242 MIKROELEKTRONIKA SOFTWARE
123. read successfully 1 if there was an error while reading The function reads 16 byte CSD register Description Parameters data csd buffer of minimum 16 bytes in length for storing CSD register content MMC SD card must be initialized See Mmc Init dim error as word dataBuffer as char 16 main error Mme Read Csd dataBuffer end 260 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc Fat Init Prototype sub function Mmc Fat Init as byte 0 if MMC SD card was detected and successfully initialized 1 if FAT16 boot sector was not found 255 if MMC SD card was not detected Initializes MMC SD card reads MMC SD FAT16 boot sector and extracts neces Description sary data needed by the library Note MMC SD card has to be formatted to FAT16 file system Mmc Chip Select Chip Select line Mmc Chip Select Direction Direction of the Chip Select pin must be defined before using this function The appropriate hardware SPI module must be previously initialized See the SPI1 Init SPI1 Init Advanced routines init the FAT library if Fat Init 0 then end if MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 261 CHAPTER 6 Libraries mikroBasic PRO for AVR Mmc Fat QuickFormat Prototype 262 Description Requires sub function Fat QuickFormat dim mmc fat label as strin
124. repu RE EE RERO GU ADORA d eae X 290 Expander Read Byte 291 Expander Write Byte 291 Expander Read 292 Expander Read PortB 292 Expander Read PortAB 293 Expander Write Port 294 Expander Write PortB 295 Expander Write PortAB 296 Expander Set DirectionPortA 297 Expander Set DirectionPortB 297 Expander Set DirectionPortAB 298 Expander Set 5 298 Expander Set 299 Expander Set PullUpsPortAB 299 Library 300 HW Connection 301 5 2 LIDIA then io te rete Cae Rene a Re Re x ae OR ea 302 External dependencies of PS 2 Library 302 Library Routines 302 Ps2 Contlg beer anre rite vore 303 Ps2 Key Read 304 Special Function Keys 305 Library
125. result is of 1ongint 140 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference STRUCTURES A structure represents a heterogeneous set of elements Each element is called a member the declaration of a structure type specifies a name and type for each member The syntax of a structure type declaration is structure structname dim memberl as typel dim membern as typen end structure where st ructname is valid identifier each type denotes a type and each member is a valid identifier The scope of a member identifier is limited to the structure in which it occurs so you don t have to worry about naming conflicts between member identifiers and other variables For example the following declaration creates a structure type called Dot structure Dot dim x as float dim y as float end structure Each Dot contains two members x and y coordinates memory is allocated when you instantiate the structure like this dim m n as Dot This variable declaration creates two instances of Dot called m and A member can be of the previously defined structure type For example Structure defining a circle structure Circle dim radius as float dim center as Dot end structure MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 141 CHAPTER 5 Language Reference mikroBasic PRO for AVR 142 Structure Member Access You can access t
126. routine Draw a circle with center in 50 50 and radius 10 SPI Gled Crrcbe 50 50 10 1 398 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI Glcd Set Font Description Requires sub procedure SPI Glcd Set Font dim activeFont as longint dim aFontWidth as byte dim aFontHeight as byte dim aFontOffs as word Nothing Sets font that will be used with SPI Glcd Write Char and SPI Glcd Write Text routines Parameters activeFont font to be set Needs to be formatted as an array of char aFontWidth Width of the font characters in dots aFontHeight height of the font characters in dots aFontOffs number that represents difference between the mikroBasic PRO character set and regular ASCII set eg if A is 65 in ASCII character and A is 45 in the mikroBasic PRO character set aFontOffs is 20 Demo fonts supplied with the library have an offset of 32 which means that they start with space The user can use fonts given in the file Lib GLCD fonts mbas file located in the Uses folder or create his own fonts Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Use the custom 5x7 font myfont which starts with space 32 SPI Gled Set Font 8myfont 5 7 32 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 399 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI Glcd Write Ch
127. special down as byte dim PS2 Data as sbit at PINC BO PS2 Clock Input as sbit at 1 PS2 Clock Output sbit at 1 PS2 Data Direction as sbit at DDRC BO PS2 Clock Direction as sbit at DDRC B1 main UART1 Init 19200 Initialize UART module at 19200 bps Ps2 Contig Init PS 2 Keyboard Delay ms 100 Wait for keyboard to finish UART1 Write Ready while TRUE T Endless loop if Ps2 Key Read keydata special down 0 then t TE data was read from PS 2 if down lt gt 0 and keydata 16 lt gt 0 then E Backspace read UART1 Write 0x08 Send Backspace to USART terminal else if down lt gt 0 and keydata 13 lt gt 0 then Enter read UART1 Write 10 Send carriage return to usart terminal UART1 Write 13 T Uncomment this line if usart terminal also expects line feed for new line transition else if down lt gt 0 and special 0 and keydata lt gt 0 lt gt 0 then Common key read UART1 Write keydata Send key to usart terminal end if end if end if end if Delay ms 10 Debounce period wend end 306 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection PS2 CONNECTOR t OSCILLATOR ul 9LVOAWNLV Example of PS2 keyboard connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 307
128. test if data is ready first MCU with the UART module Requirss The UART module must be initialized before using this routine See UARTXx Init routine dim receive as byte read data if ready if UART1 Data Ready 1 then receive UART1 Read 472 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries UARTx Read Text Prototvpe sub procedure UARTx Read Text dim byref Output as stringi 255 yp dim byref Delimiter as string 10 dim Attempts as byte Reads characters received via UART until the delimiter sequence is detected The read sequence is stored in the parameter output delimiter sequence is stored in the parameter delimiter Description This is a blocking call the delimiter sequence is expected otherwise the proce dure exits if the delimiter is not found Attempts defines number of received characters in which Delimiter sequence is expected If Attempts is set to 255 this routine will continously try to detect the Delimiter sequence UART HW module must be initialized and communication established before using this function See UARTx_Init Read text until the sequence OK is received and send back what s been received UART1 Init 4800 initialize UART module Delay ms 100 while TRUE if UART1 Data Ready 1 if data is received UARTI Read Text output delim 10 reads text until delim is found UART1 Write Text output s
129. the ENC28J60 tion as sbit sfr external dim chip select pin SPI Ethernet RST Dire Direction of the ENC28J60 ction as sbit sfr external The following routines must be defined in all project using SPI Ethernet Library sub function Spi Ethernet UserTCP dim remoteHost as byte remotePort as word localPort as word regLength as word as word dim mikroBasic PRO for AVR dim SPI Ethernet CS as sbit at PORTB B4 dim SPI Ethernet RST as sbit at PORTB B5 Ethernet CS Direc ion as sbit at DRB B4 Ethernet RST Dire tion as sbit at DRB B5 Description Refer to the library example at the bottom TCP request dim dim sub function Spi Ethernet UserUDP dim remoteHost as byte as word word word as word dim remotePort handler of this page for code implementation Refer to the library example at the bottom UDP request dim destPort as dim regLength as handler of this page for code implementation 368 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Library Routines Spi Ethernet Init Spi Ethernet Enable Spi Ethernet Disable Spi Ethernet doPacket Spi Ethernet putByte Spi Ethernet putBytes Spi Ethernet putString Spi Ethernet putConstString Spi Ethernet putConstBytes Spi Ethernet getByte Spi Ethernet getBytes Spi Ethernet User
130. this might not seem important but it is important when you are capturing matched text using parentheses Also remember that is inter preted as a literal within square brackets so if you write bit bat bot you re really only matching biao Examples rou tine te matches strings routine route Metacharacters Subexpressions The bracketing construct may also be used for define regular subexpres sions Subexpressions are numbered based on the left to right order of their open ing parenthesis First subexpression has number 1 Examples int 8 10 matches strings which contain 8 9 or 10 instances of the int routi 0 9 a e matches routiOe routile s routine routinne routinnne etc Metacharacters Backreferences Metacharacters 1 through 9 are interpreted as backreferences matches previ ously matched subexpression Examples 1 matches aaaa and 1 matches abab and 123123 12 1 matches 13 in double quotes or 4 in single quotes or 77 without quotes etc 66 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment MIKROBASIC PRO FOR AVR COMMAND LINE OPTIONS Usage mBAvr exe opts lt opts gt zmfzie opts lt gt 1 Infile can be of mbas and c1 type The following parameters and some more see manual are valid P MCU fo
131. to be initialized see Glcd Init routine Requires Glcd side x axis position and page should be set first See functions Glcd_Set_Side Glcd Set X and Glcd_Set_Page dim data as byte data Glcd Read Data 222 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Glcd Write Data Prototype sub procedure Glcd Write Data dim as byte Writes one byte to the current location in Glcd memory and moves to the next location Description Parameters ddata data to be written Glcd needs to be initialized see Glcd Init routine Glcd side x axis position and page should be set first See functions Glcd Set Side Glcd Set X and Set Page dim data as byte Glcd Write Data data Glcd Fill Prototype sub procedure Glcd Fill dim pattern as byte Fills Glcd memory with the byte pattern Parameters Description pattern byte to fill Glcd memory with To clear the Glcd screen use Fill 0 To fill the screen completely use Fiil 0xFF Glcd needs to be initialized see Glcd Init routine Clear screen Gled RILT MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 223 CHAPTER 6 Libraries mikroBasic PRO for AVR Glcd Dot sub procedure Glod Dot dim x pos as byte dim y pos as byte dim color as byte Prototype Draws a dot on Glcd at coordinates x pos y pos Parameters
132. to the nearest integer result round cos angle deg 1000 Description Parameters angle deg input angle in degrees Note Return value range 1000 1000 Requires Nothing dim res as integer res cosE3 196 result is 193 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 499 admis y EXCESS NEM I C C IGP fm 1 eee mee UJO2 90J3IUJ9 921JJO IeUU 9 yoddns ua wo 301 OCW VMN 1404415 TVDINHDIL 2 D f C VU O AN C OOOOOO O O O Li O OOO O MOU SN ja esea d uorjeuuojur jeuonippe 3uew snf no JO syonpoud sno Aue suajqoid nof j 5 12e3u02 eseejd Jesodoud ssauisnq e 10 3usuuu02 uonsenb 13470 Aue NOK j SNOLLO1OS 38 ANY 348vM14OS exu nyao MNIE Mouser Electronics Authorized Distributor Click to View Pricing Inventory Delivery amp Lifecycle Information mikroElektronika MIKROE 722
133. 0 48 Extract tens digit text 2 temp whole mod 10 48 Extract ones digit extract temp fraction and convert it to unsigned int temp fraction word temp2write 4 RES SHIFT temp fraction temp fraction and 0 000 temp fraction temp fraction 625 convert temp fraction to characters text 4 word temp fraction div 1000 48 Extract thousands digit Extract hundreds digit text 5 word temp fraction div 100 mod 10 48 i text 6 word temp fraction div 10 mod 10 48 Extract tens digit text 7 word temp fraction mod 10 48 Extract ones digit print temperature on Lcd hed Out 2 5 text end sub main text 000 0000 UART1 Init 9600 Led Inst Initialize Lcd Lcd Cmd LCD CLEAR V gar Led Lcd Cmd LCD CURSOR OFF cursor off Led Out l 1 Temperature y Print degree character C for Centigrades Log Chr 2 13 178 different Lcd displays have different char code for degree 178 if you see greek alpha letter try typing instead of 223 Led Chr 2 14 C while TRUE main loop 286 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR perform temperature reading wend end MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Ow Reset Onewire reset Ow Write 0xCC Issue command Ow Write 0x44 Issue command Delay us 120 Ow Rese
134. 101 Constant 0 1 101 Constant propagation 101 Copy propagation 101 Value numbering rm RR DERE ROG PENA ROPA ERA 101 VIII MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Table of Contents Dead code ellimination 101 Stack allocation 101 Local vars optimization 101 Better code generation and local optimization 101 Types 103 CHAPTER 4 Nested Calls Limitations 104 Important 104 AVR Memory Organization 105 Program Memory 105 Data Memory simae Puch dus Ein 105 Memory Type Specifiers 107 IANUE ERES RS iei a ebbe ecce stu aser 107 data PP 107 IX phi edi booted 107 ee ace 108 s y ec EX EN a ob mde nts A 108 GgISLOl por ord nimbis velie Peg dud ded daddies 108 Dor iced 4 oak e er eg 108 CHAPTE
135. 2 U 8 ver 2 0 1 27012005 System status Win NT like OS MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 57 CHAPTER 2 Environment mikroBasic PRO for AVR Lcd Custom Character mikroBasic PRO for AVR includes the Lcd Custom Character Output is mikroBasic PRO for AVR compatible code You can launch it from the drop down menu Tools Lcd Custom Character Ex Load Fill all Clear all Invert Preview d C 5x10 cursor line A B CGRAM address Char Char data row 58 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment MACRO EDITOR A macro is a series of keystrokes that have been recorded in the order performed A macro allows you to record a series of keystrokes and then playback or repeat the recorded keystrokes Macros 2 b Macro3 The Macro offers the following commands Description Starts recording keystrokes for later playback Stops capturing keystrokesthat was started when the Start Recordig com mand was selected Allows a macro that has been recorded to be replayed New macro lt Delete macro Icon 42 di Related topics Advanced Code Editor Code
136. 2 2 306 HW Connection 307 EE 308 Library RoutineS 308 Predefined constants used in PWM library 308 Rela 310 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XVII Table of Contents mikroBasic PRO for AVR PWM Set D lty e DE bI recte A 311 PWM ree Dave OR bd riae dada 311 PWM SOD sedere DR ceat pre ER aca CR oa UE EA ATTE 312 PWM1 ease REEL EP i be ee qd 312 PWM1 Set 314 PWM1 314 OP nacre deg Rer iE RETE RIP ERR RR ERR 314 Library Example 2 0 0 e000 252 2245 225555545 eR E 315 HW Connection 316 PWM 16 bit Library 2 317 Library RoutineS 317 Predefined constants used PWM 16bit library 318 PWM16bit_Init 22 00 00 sce iit em mr dx Rd 319 PWM16bit Change Duty 321 PWMY196bit Start ius 322 PWMnA6DbIE SIOD aru ttd ice tele eee 322 Library Example iere Rp betel 322 The example changes PWM duty ratio continuall
137. 3 the return value is 0 end A function can return a complex type Follow the example bellow to learn how to declare and use a function which returns a complex type Example This example shows how to declare a function which returns a complex type program Example structure TCircle Structure dim CenterX CenterY as word dim Radius as byte end structure dim MyCircle as TCircle Global variable sub function DefineCircle dim x y as word dim r as byte as TCircle DefineCircle function returns a Structure tesult Centerx x result Centeri y result Radius r end sub main MyCircle DefineCircle 100 200 30 Get a Structure via function call MyCircle CenterX DefineCircle 100 200 30 CenterX 20 T Access a Structure field via function call 2225 Function returns TCircle Access to one field of TCircle end 134 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference Forward declaration A function can be declared without having it followed by it s implementation by hav ing it followed by the forward procedure The effective implementation of that func tion must follow later in the module The function can be used after a forward dec laration as if it had been implemented already The following is an example of a for ward declaration program Volume dim Volume
138. 3C Set Cursor cposx cposy T6963C DisplayGrPanel Prototype sub procedure T6963C DisplayGrPanel dim n as byte Display selected graphic panel Description Parameters n graphic panel number Valid values 0 and 1 Toshiba module needs to be initialized See the T6963C Init routine display graphic panel 1 T6963C DisplayGrPanel 1 T6963C DisplayTxtPanel Prototype sub procedure 6963 DisplayTxtPanel dim n as byte Display selected text panel Description Parameters n text panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See the T6963C Init routine display text panel 1 T6963C DisplayTxtPanel 1 454 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries T6963C SetGrPanel Prototype sub procedure 6963 SetGrPanel dim n as byte Nothing Compute start address for selected graphic panel and set appropriate internal pointers All subsequent graphic operations will be preformed at this graphic panel Description Parameters n graphic panel number Valid values 0 and Toshiba Glcd module needs to be initialized See the T6963C Init routine Example set graphic panel 1 as current graphic panel T6963C SetGrPanel 1 T6963C SetTxtPanel Prototype sub procedure T6963C SetTxtPanel dim n as byte Nothing Compute start address for selected text panel and set appro
139. 4 i 4 else strt cehr 34 lt td bgcolor cccccc gt OFF t chr 34 strecs 4ochr 34 4 e td td s a href t chr 34 4i chr 34 gt Toggql lt a gt lt td gt lt tro cehr 34 document write str lt script gt lt table gt lt td gt lt tr gt lt table gt This is HTTP request script document write REQ script BODY HTML dim getRequest byte 15 HTTP request buffer dyna as byte 31 buffer for dynamic response httpCounter as word counter of HTTP requests sub function SPI Ethernet UserTCP dim byref remoteHost as byte 4 dim remotePort localPort reqLength as word as word sub function SPI Ethernet UserUDP dim byref remoteHost as byte 4 dim remotePort destPort reqLength as word as word implements Vok ck ck Ckck ck Ck ck ck ck Ck ck Ck Ck kk ck kk ck ko kk Ck ck kk ck ko kc k kc ko user defined sub functions LE put the constant string pointed to by s to the transmit buffer sub function putConstString dim const s as byte as word result 0 while s lt gt 0 SPI Ethernet putBbyte s ime Ss Inc result wend end sub 384 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries put the string pointed to s to the transmit buffer sub function putString dim byref s as byte 100 as word result
140. 5 while counter 60 Draw horizontal and vertical line Delay ms 250 SPI Gled V Line 2 54 counter 1 SPI Cled H 2 120 Counter 1 counter counter 5 wend Delay2s SPI Glcd Fill 0x00 Clear Gled SPI Gled Set Font G8Character8x7 8 8 32 Choose font Character8x7 SPI Cled Write Text 5 Ty 2 Write string for counter 1 to 10 Draw circles SPI Gled Circle f63 92 3 counter 1 next counter Delay2s SPI Gled Box 12 20 70 63 2 Draw box Delay2s MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 403 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI Fill OxFF Fill Gled SPI Gled Set Font GCharacter8x7 8 7 32 Change font someText 8x7 Font SPI Gled Write Text someText 5 1 2 Write string Delay2s SPI Gled Set Font G8System3x6 3 5 32 Change font someText 3X5 CAPITALS ONLY SPL Gled Write Text someText 5 3 2 Write string Delay2s SPI Gled Set Font Gfontbx 5 7 32 Change font someText 5x7 Font SPI Gled Write Text someText 5 5 2 Write string Delay2s SPI Cled Set Font GFontSystem5x7 v2 5 T 32 Change font someText 5x7 Font v2 SPI Gled Write T xt someText S Fy 2 Write string Delay2s wend end 404 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection Left side Rightside wr X
141. 5540 dnsIpAddr as byte 4 DNS server IP address E ehternet NIC pinout PI Ethernet Rst sbit at PORTB B4 m S SPI Ethernet CS as sbit at PORTB B5 S S PI Ethernet Rst Direction as sbit at DDRB B4 PI Ethernet CS Direction as sbit at DDRB B5 end ethernet NIC definitions dim i as word main set PORTC as input DDRC 0 set PORTD as output DDRD OxFF httpCounter 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 381 CHAPTER 6 Libraries mikroBasic PRO for AVR myMacAddr 0 0x00 myMacAddr 1 0x14 myMacAddr 2 0 5 myMacAddr 3 0x76 myMacAddr 4 0x19 myMacAddr 5 0x3F 0 192 myIpAddr 1 168 myIpAddrzr 2 20 myIpAddr 3 60 gwlpAddr 0 192 gwlpAddr 1 168 gwlpAddr 2 20 gwlpAddr 3 6 ipMask 0 255 ipMask 1 255 ipMask 2 255 ipMask 3 0 dnsIpAddr 0 192 dnsIpAddr 1 168 dnsIpAddr 2 20 dnsIpAddr 3 1 3 starts 28060 with reset bit on 4 T Ce BIE oh PORTB B 1 my amp IP address d full duplex SPI1 Init Advanced SPI MASTER SPI DIV2 SPI LO LEAD ING SPI Rd Ptr SPI1_ Read SPI Ethernet UserTCP Ptr GSPI Ethernet UserTCP SPI Ethernet UserUDP Ptr CSPI Ethernet UserUDP SPI Ethernet Init myMacAddr myIpAddr SPI Ethernet FULLDUPLEX dhcp will not be used here so use preconfigured addresses SP
142. 63C ctrlwr Direction as sbit at DDRC B2 WR write sig nal direction dim T6963C ctrlrd Direction as sbit at 1 RD read sig nal direction dim 6963 ctrlcd Direction as sbit at DDRC BO CD command data signal direction dim T6963C ctrlrst Direction as sbit at DDRC B4 RST reset signal direction Signals not used by library they are set in main sub function dim T6963C ctrlce as sbit at PORTC B3 CE signal dim 6963 ctrlfs as sbit at PORTC B6 signal dim 6963 ctrlmd as sbit at PORTC B5 MD signal dim T6963C ctrlce Direction as sbit at DDRC B3 CE signal direction dim T6963C ctrlfs Direction as sbit at DDRC B6 FS signal direction dim T6963C ctrlmd Direction as sbit at DDRC B5 MD signal direction End T6963C module connections dim panel as byte current panel i as word general purpose register curs as byte cursor Visibility curser x y position txtcols as byte number of text coloms txt txtl as stringi 29 txtl EINSTEIN WOULD HAVE LIKED mE txt GLCD LIBRARY DEMO WELCOME MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 459 CHAPTER 6 Libraries mikroBasic PRO for AVR 460 DDRA 0x00 DDAO bit DDAI bit DDA2 bit DDA3 bit DDA4 bit exc Cc O T69630 crtrloce Direction 1 T69630 otrlo Q T69630 ctflfs Direction 1 T69630 cttlfs 0 T6963C crtrlmd
143. 6963C NegBit Prototype sub procedure SPI T6963C negBit dim b as byte Nothing Negates control port bit s Parameters Description b bit mask The function will negate bit on control port if bit x in bit mask is set to 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine negate bits 0 and 1 on control port SPI T6963C NegBit 0x03 SPI T6963C DisplayGrPanel Prototype sub procedure SPI T6963C DisplayGrPanel dim n as byte Nothing Display selected graphic panel Description Parameters n graphic panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine display graphic panel 1 SPI T6963C DisplayGrPanel 1 SPI T6963C DisplayTxtPanel Prototype sub procedure SPI T6963C DisplayTxtPanel dim n as byte Nothing Display selected text panel Description Parameters n text panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine display text panel 1 SPI T6963C DisplayTxtPanel 1 432 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI T6963C SetGrPanel Prototype sub procedure SPI T6963C SetGrPanel dim n as byte Nothing Compute start address for selected graphic panel and set appropriate internal pointers All subsequent graphic operations will be preformed at th
144. 963C Config routine Ease m T6963C Circle 120 10 T6963C WHITE MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 429 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI T6963C Image Prototype sub procedure SPI T6963C image const pic as byte Displays bitmap on Glcd Parameters pic image to be displayed Bitmap array can be located in both code and Description RAM memory due to the mikroBasic PRO for AVR pointer to const and pointer to RAM equivalency Use the mikroBasic PRO s integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for display ing on Glcd Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Emme SPI T6963C Sprite Prototype sub SPI T6963C sprite dim px sx sy as byte const pic as byte Fills graphic rectangle area px py to px sx py sy with custom size picture Parameters px X coordinate of the upper left picture corner Valid values multiples of the font width Description y coordinate of the upper left picture corner pic picture to be displayed sx picture width Valid values multiples of the font width sy picture height Note and sx parameters are not multiples of the font width they will be scaled to the nearest lower number that is a multiple of the font width Toshiba Glcd module needs to be i
145. 963C dataPort Direc tion as byte sfr external dim T6963C ctrlPort Direo tion as byte sfr external dim Teves Direct on as sbit sfr external dim T6963C ctrlrd Directi on as sbit sfr external dim T6963C ctrlod Directs on as sbit sfr external dim T9620 octrlrst Dursect ion as sbit sfr external Description Direction of the T6963C Direction of the T6963C Control Port Direction of the Write pin Direction of the Read pin Direction of the Com mand Data pin Direction of the Reset pin T6963C dataPort as s byte at PORTD T6963C cirlPort as s byte at PORTC wr as rd as cd as T6963C ctrlrst as e at PORTC B4 dim T6963C dataPort Direc tion as byte at DDRD dim T6963C cirlPort Direc tion as byte at DDRC dim T6963C ctrlwr Directi on as sbit at DDRC B2 dim T6993C ctrlrd Directa on as sbit at DDRC B1 dim T6963C ctrlod Directi as sbit at DDRC BO dim 09090 ctrltst Direct ion as sbit at DDRC B4 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 443 CHAPTER 6 Libraries mikroBasic PRO for AVR Library Routines T6963C Init T6963C WriteData T6963C WriteCommand T6963C SetPtr T6963C WaitReady T6963C Fill T6963C Dot T6963C Write Char T6963C Write Text T6963C Line T6963C Rectangle T6963C Box T6963C Circle T6963C Image T6963C Sprite T6963C Set Cursor T6963C DisplayGrP
146. ARTI Write Text r Starto Init the FAT library eee use Cf Fat OuickPormat instead of init routine if a mat is needed if Cf Fat Init 0 then test sub functions pesce test group 1 Create New File Create Multiple Piles test group 2 Open File Open File Append Delete File test group 3 Open File Read Test File Exist Create Swap Pile Test termination UART1 Write 0xAA else UART1 Write Text FAT TXT end if signal end of test VARTI Write Text End MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 209 for CHAPTER 6 Libraries mikroBasic PRO for AVR HW Connection oc OSCRLATOR 4l Compact Flash Card Be ees SSS S S BSGPHSISSRENERRE ee OILL lt a Pin diagram of CF memory card 210 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries EEPROM LIBRARY EEPROM data memory is available with a number of AVR family The mikroBasic PRO for AVR includes a library for comfortable work with MCU s internal EEPROM Note EEPROM Library functions implementation is MCU dependent consult the appropriate MCU datasheet for details about available EEPROM size and address range Library Routines EEPROM Read EEPROM Write EEPROM Read Prot
147. ATE current system date STIMES current system time DEVICES device MCU name as specified in project settings DEVICE CLOCKS Clock as specified in project settings SCOMPILERS current compiler version These macros be used in template code see template pt emplate provided with mikroBasic PRO for AVR installation Auto Correct The Auto Correct feature corrects common typing mistakes To access the list of rec ognized typos select Tools Options from the drop down menu or click the Show Options Icon Af and then select the Auto Correct Tab You can also add your own preferences to the list Also the Code Editor has a feature to comment or uncomment the selected code by sim ple click of a mouse using the Comment Icon 1 and Uncomment Icon 1 from the Code Toolbar 38 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Spell Checker The Spell Checker underlines unknown objects in the code so it can be easily noticed and corrected before compiling your project Select Tools Options from the drop down menu or click the Show Options Icon and then select the Spell Checker Tab Bookmarks Bookmarks make navigation through a large code easier To set a bookmark use Ctrl Shifttnumber To jump to a bookmark use Ctrl number Goto Line The Goto Line option makes navigation through a large code easier Use t
148. ATES FIRST AND OBTAINED A RETURN AUTHORIZATION NUMBER This Limited Warranty is void if failure of Software has resulted from an accident abuse or misapplication Any replacement of Software will be warranted for the rest of the original warranty period or thirty 30 days whichever is longer TO THE MAXIMUM PERMITTED BY APPLICABLE LAW MIKROELEKTRONIKA ASSOCIATES AND ITS SUPPLIERS DISCLAIM ALL OTHER WARRANTIES AND CONDITIONS EITHER EXPRESSED OR IMPLIED INCLUDED BUT NOT LIMITED TO IMPLIED WARRANTIES MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE TITLE AND NON INFRINGEMENT WITH REGARD TO SOFTWARE AND THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES IN NO EVENT SHALL MIKROELEKTRONIKA ASSOCIATES OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL INCIDENTAL INDIRECT OR CONSEQUENTIAL DAMAGES WHATSOEVER INCLUDING WITHOUT LIMITATION DAMAGES FOR LOSS OF BUSINESS PROFITS AND BUSINESS INFORMATION BUSINESS INTERRUPTION OR ANY OTHER PECUNIARY LOSS ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE PRODUCT OR THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES EVEN IF MIKROELEKTRONIKA ASSOCIATES HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES IN ANY CASE MIKROELEKTRONIKA ASSOCIATES ENTIRE LIABILITY UNDER ANY PROVISION OF THIS LICENSE AGREEMENT SHALL BE LIMITED TO THE AMOUNT ACTUALLY PAID BY YOU FOR SOFTWARE PRODUCT PROVIDED HOWEVER IF YOU HAVE ENTERED INTO A MIKROELEKTRONIKA ASSOCIATES SUPPORT SERVICES
149. Append 266 Mmc Fat Delete 266 Mme Fat Write ceux des we M RA UA 267 Mmc Fat Set _ 268 Mmc Fat Get File 269 Mmc Fat Get File Size 270 Mmc Fat Get 5 _ 271 Library Example 22 s isis iil em emn med dee had 273 HW Connection 280 OneWire 1 4 4 ee 281 External dependencies of OneWire 281 Library Routines 281 OW RESET Lucca es RR RR Rha 282 XVI MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Table of Contents OW Read gt 283 OW Writes pag ia tata dai dose d E du 284 Library 285 HW Connection 222 REA RE AGE 288 Port Expander Library 289 External dependencies of Port Expander Library 289 Library Roultines asd ds xa E Rer ERU Reeds 289 Expander nites 21 06 ese
150. BIT as byte 10 CANSPI CONFIG DBL BUFFER ON as byte FF XXX1XXXX CANSPI CONFIG DBL BUFFER OFF as byte SEF XXX0XXXX CANSPI CONFIG MSG BITS as byte 60 CANSPI CONFIG ALL MSG as byte FF X11XXXXX CANSPI CONFIG VALID XTD MSG as byte DF X10XXXXX CANSPI CONFIG VALID STD MSG as byte BF 01 CANSPI CONFIG ALL VALID MSG as byte 9F You may use bitwise and to form config byte out of these values For example init CANSPI CONFIG SAMPLE THRICE and CANSPI CONFIG PHSEG2 PRG ON and CANSPI CONFIG STD MSG and CANSPI CONFIG DBL BUFFER ON and CANSPI CONFIG VALID XTD MSG and CANSPI CONFIG LINE FILTER OFF CANSPIInit 1 Es Sy Ge Loo Aniti initialize CANSPI CANSPI TX MSG FLAGS CANSPI TX MSG FLAGS are flags related to transmission of a CAN message const CANSPI TX PRIORITY BITS as byte 503 CANSPI TX PRIORITY 0 as byte XXXXXX00 CANSPI TX PRIORITY 1 as byte SFD XXXXXX01 CANSPI TX PRIORITY 2 as byte XXXXXX10 CANSPI TX PRIORITY 3 as byte SFF XXXXXX11 CANSPI TX FRAME BIT as byte 08 CANSPI TX STD FRAME as byte XXXXX1XX CANSPI TX XTD FRAME as byte SF7 XXXXXOXX CANSPI TX RTR BIT as byte 540 CANSPI TX NO RTR FRAME as byte SFF CANSPI TX RTR FRAME as byte SBF XOXXXXXX You may use bitwise and to adjust the appropriate flags For example
151. CTRL while dragging it Saving Layout Once you have a window layout that you like you can save the layout by typing the name for the layout and pressing the Save Layout Icon d To set the layout select the desired layout from the layout drop down list and click the Set Layout Icon To remove the layout from the drop down list select the desired layout from the list and click the Delete Layout Icon jag Default Layout Code Layout Debug Layout layout Mi MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 33 CHAPTER 2 Environment mikroBasic PRO for AVR Auto Hide Auto Hide enables you to see more of your code at one time by minimizing tool win dows along the edges of the IDE when not in use Click the window you want to keep visible to give it focus Click the Pushpin Icon on the title bar of the window Project Manager dcs 551181 7 9 i 4 5 FirstProject mbpav 7j Sources SecondProject mbas Binaries C73 Project level defines 73 Image Files E Output Files E Other Files 4 POP 4 Sour B e petoag Jebeuej palog 177 When an auto hidden window loses focus it automatically slides back to its tab on the edge of the IDE While a window is auto hidden its name and icon are visible on a tab at t
152. Cf Read Sector 22 data Cf Write Sector Prototvpe sub procedure Cf Write Sector dim sector number as longword dim buffer as byte 5121 Writes 512 bytes of data provided by the buffer parameter to one CF sector Description Parameters sector number sector to be written to buffer data buffer of 512 bytes in length ooo MCU ports must be appropriately initialized for CF card See write to sector 22 dim data as array 512 of byte Gf Write Sector 22 data 196 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Cf Fat Init Prototype sub function Cf Fat Init as byte 0 if CF card was detected and successfully initialized 1 if FAT16 boot sector was not found 255 if card was not detected Initializes CF card reads CF FAT16 boot sector and extracts data needed by Description the library init the FAT library if Fat 101 0 then end if Cf Fat QuickFormat sub function Cf Fat QuickFormat dim byref cf fat label as string 11 as byte 0 if CF card was detected successfully formated and initialized 1 if FAT16 format was unseccessful 255 if card was not detected Formats to FAT16 and initializes CF card Parameters cf fat label volume label 11 characters in length If less than 11 characters are provided the label will be padded with spaces If an empty string is pa
153. Db 435 SPI 769636 Qursor be 436 SPI T6963C Cursor Blink 436 Library 2 2 22 2 4 0 16 436 The following drawing demo tests advanced routines of the 5 436 HW Connection 441 SPI T6963C Graphic Lcd 442 External dependencies of T6963C Graphic Lcd Library 443 Library Routines 444 ars gant Race Reds 445 XXII MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Table of Contents T6963C WriteData 446 T6963C WriteCommand 447 TOY SEPI 447 T6963C WaitReady 447 T6963C_ Fills 2 2 eme tm m maed sey ane 448 16963C Dot gt eben Ren E ER hee x bees 448 T6963C Write Char aa une ts okey awe peewee awa RUE 449 T6963C Write Text ccs EX 4E ERR 4 RARE 450 T69636C Lite rh es ca RR 451 T6963C Rectangle usa mee hk RR eT 451 T16963C BOX fess catia eo eA wae p du e on e elena e A 452 16963C CE 452 T6963C Image i 2 Dei bad tetas 453 169636 Sptlte cre
154. Direction 1 T6963C otrimd 0 panel 0 i 0 curs 0 cposx 0 cposy 0 Initialize T6369C T6963C inte 240 129 8 Enable both graphics and T6963C graphics 1 T6963C text 1 Text messages my 769636 write text txt 0 0 configure PORTA as input Set Set Set Set Set as PBI as PB2 as PB3 as 4 as input input input input input Enable T6963C Font Select 8x8 Column number select text display at the same time T6963C ROM MODE XOR T6963C write text txtl 0 15 T6963C ROM MODE XOR Cursor TI T6963C cursor herghit 8 9 pixel height T6963C set cursor 0 Move cursor to top left T6963C cursor 0 Cursor off Draw rectangles jd 769630 rectangle 0 0 239 121 T6963C WEITE T6963C rectangle 20 20 219 107 T6963C WHITE T6963C rectangle 40 40 199 87 T6963C WHITE T6963C rectangle 60 60 179 67 T6963C WHITE MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR 1 a T69630 Line 0 T6963C line 0 i T6963C box 0 0 239 T6963C box 0 IIS while true do nop i ii T6963C circle 120 T6963C 120 T69630 carele 120 T6963C Crrele 120 Draw a cross 0 239 Draw solid boxes Draw circles 64 64 64 64 64 64 T6963C circle 120 T6963C
155. E vera ha 425 SPI T6963C 425 SPI T6963C Write Char 426 6963 427 6963 cassa et IRR Re EE eee en es 428 SPI T6963C Rectangle 428 SPI T6963G BOX ecu awe oa Rae ee ae ee 429 SPI T6963C 2 22222 224 429 SPI T6963C Image 430 T6963C 430 SPI T6963C Set Cursor 431 SPI T6963C ClearBit 431 SPI T6963C eee acetic 431 SPI T6963C 432 SPI T6963C DisplayGrPanel 432 SPI T6963C DisplayTxtPanel 432 SPI T6963C SetGrPanel 433 SPI T6963C 433 SPI T6963C PanelFill 434 SPI T6963C 434 SPI T6963C eee 434 6963 435 SPI T6963C Graphics 435 SPI T6963C e xm tn X
156. ELSEIF resolutionl2 THEN code specific to 12 bit resolution ELSE default code ENDIF Predefined Flags The compiler sets directives upon completion of project settings so the user does n t need to define certain flags Here is an example IFDEF ATMEGA16 If ATmegal6 MCU is selected IFDEF 128 If ATmegal28 MCU is selected In some future releases of the compiler the JTAG flag will be added also See also predefined project level defines MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 165 CHAPTER 5 Language Reference mikroBasic PRO for AVR LINKER DIRECTIVES mikroBasic PRO for AVR uses internal algorithm to distribute objects within memo ry If you need to have a variable or routine at the specific predefined address use the linker directives absolute and org Note You must specify an even address when using the linker directives Directive absolute The directive absolute specifies the starting address in RAM for a variable If the variable spans more than 1 word 16 bit higher words will be stored at the consec utive locations The absolute directive is appended to the declaration of a variable dim x as word absolute 0x32 Variable x will occupy 1 word 16 bits at address 0x32 dim y as longint absolute 0x34 Variable y will occupy 2 words at addresses 0x34 and 0x36 Be careful when using absolute directive as
157. ES LICENSE STATEMENT AND LIMITED WARRANTY IMPORTANT READ CAREFULLY This license statement and limited warranty constitute a legal agreement License Agreement between you either as an individual or a single entity and mikroElek tronika mikroElektronika Associates for software product Software identified above including any software media and accompanying on line or printed docu mentation BY INSTALLING COPYING OR OTHERWISE USING SOFTWARE YOU AGREE TO BE BOUND BY ALL TERMS AND CONDITIONS OF THE LICENSE AGREEMENT Upon your acceptance of the terms and conditions of the License Agreement mikroElektronika Associates grants you the right to use Software in a way provided below This Software is owned by mikroElektronika Associates and is protected by copy right law and international copyright treaty Therefore you must treat this Software like any other copyright material e g a book You may transfer Software and documentation on a permanent basis provided You retain no copies and the recipient agrees to the terms of the License Agreement Except as provided in the License Agreement you may not transfer rent lease lend copy modify translate sublicense time share or electronically transmit or receive Software media or documentation You acknowledge that Software in the source code form remains a confidential trade secret of mikroElektronika Associates and therefore you agree not to modify Software or attemp
158. ExpanderCS as sbit at PORTB B1 SPExpanderRST as sbit at PORTB BO SPExpanderCS Direction as sbit at DDRB B1 SPExpanderRST Direction as sbit at DDRB BO epil Tnit Initialize spi interface Spi Rd Ptr SPI1 Read Pass pointer to SPI Read function of used SPI module SPI Leds Confug 0 r Intialise log in 8bit mode via spi 414 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI Lcd8 Out sub procedure SPI Lcd8 Out dim row as byte dim column as byte dim byref text as string 19 Prints text on Lcd starting from specified position Both string variables and liter als can be passed as a text Prototype Description Parameters row Starting position row number column Starting position column number text text to be written Requires Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routines Write text Hello on Lcd starting from row 1 column 3 SPI Lcd8 Out 1 3 Hello SPI Lcd8 Out Cp Prototype sub procedure SPI Lcd8 Out CP dim text as string 19 Prints text on Lcd at current cursor position Both string variables and literals can be passed as a text Parameters text text to be written Requires Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routines Write text Here at current cursor position SPL Leds Ouk OP H amp relt MIK
159. ExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function SPI module needs to be initialized See SPI1 Init and SPI1 Init Advanced routines port expander pinout definition dim SPExpanderCS sbit at PORTB B1 SPExpanderRST as sbit at PORTB BO SPExpanderCS Direction as sbit at DDRB B1 SPExpanderRST Direction as sbit at DDRB BO nati initialize SPI module Hd Ptr 8SPII Read Pass pointer to SPI Read function of used SPI module Expander Init 0 initialize port expander MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Expander Read Byte Prototvpe sub function Expander Read Byte dim ModuleAddress as byte dim yp RegAddress as byte as byte The function reads byte from Port Expander Parameters Description ModuleAddress Port Expander hardware address see schematic at the bottom of this page RegAddress Port Expander s internal register address Port Expander must be initialized See Expander Init Read a byte from Port Expander s register dim read data as byte read data Expander Read Byte 0 1 Expander Write Byte sub procedure Expander Write Byte dim ModuleAddress as byte dim RegAddress as byte dim Data as byte Nothing Routine writes a byte to Port Expan
160. FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries if size lt gt 0 then LongIntToStr size fat txt UART1 Write Text fat txt for i 0 to 4999 Mmc Write Sector size Buffer size size 1 UART1 Write next i end if end sub ain Uncomment the sub function s to test the desired operation s main FAT TXT FATI6 not found file contents XX MMC SD FAT16 library by Anton Rieckert file contents 41 10 newline filename MIKROOOxTXT we will use PORTC to signal test end DDRC OxFF PORTC 0 UART1 Init 19200 delay ms 100 Set up USART for file reading UARTI Write Text Start gt nit the EAT library SPI1_ Init Advanced SPI MASTER SPI DIV128 SPI IO LEADING Spi Rd Ptr 65 1 Read use fatl6 quick format instead of init routine if a formatting is needed if Mmc Fat Init 0 then PORTC OxFO reinitialize spi at higher speed SPI1 Init Advanced SPI MASTER SPI FCY SPI CLK IO LEADING signal staert of tesk test sub functions Create New File Create Multiple Files Open File Rewrit Open File Append Open File Read Delete File Test File Exist Create Swap UART1 Write e else UART1 Write Text FAT TXT end if signal end of test PORTC SOF UART1 Write Text End end MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 279
161. I Ethernet confNetwork ipMask gwIpAddr dnsIpAddr while TRUE do forever SPI Ethernet doPacket process incoming Ethernet packets add your stuff here if needed SPT Ethernet doPacket must be called as often possible otherwise packets could be lost T wend end 382 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR CHAPTER 6 Libraries Module eth enc28j60 utils code module eth 28160 utils kk ck kk kk ke kk ck ko kk ROM constant strings ck ck kk ck ko kk ck ke kk ck ko ko ko kk ko ko ko ko const httpHeader as string 30 HTTP 1 1 200 OK chr 10 Content type HTTP header const httpMimeTypeHTML as string 13 text html chr 10 ehr 10 HTML MIME type const httpMimeTypeScript as string 14 text plain chr 10 10 TEXT MIME type const httpMethod as string 5 GET web page splited into 2 parts when coming short of ROM fragmented data is handled more effi ciently by linker this HTML page calls the boards to get its status and builds itself with javascript const as string 513 lt meta http equiv Chr 34 refresh Chr 34 content Che 34 3 urlShttp 192 168 20 60 Chr 34 gt lt HTML gt lt HEAD gt lt HEAD gt lt BODY gt
162. INB 6 lt gt Tone2 while nop wend end if PINB if PINE S lt gt Tone3 while nop wend end if PINB Af PINB 4 lt gt Melody2 while PINB nop wend end if if PINB 3 lt gt Melody while nop wend end if wend end 360 PINB 1000 0 then 1 lt gt 0 0 then 265 10 0 then gt n 0 then d lt gt 0 0 then Configure PORTB as input Initialize sound pin 1 sec Play starting sound 2kHz endless loop If PORTB 7 is pressed play Tonel Wait for button to be released If PORTB 6 is pressed play Tone2 Wait for button to be released If PORTB 5 is pressed play Tone3 Wait for button to be released If 4 is pressed play Melody2 Wait for button to be released If PORTB 3 is pressed play Melody Wait for button to be released MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection PIEZO SPEAKER VCC i PORTB B3 95 PORTB B4 o gt im ON D PORTB B6 lt a PORTB B7 O Example of Sound Library sonnection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 361 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI LIBRARY mikroBasic PRO for AVR provides a library for comfort
163. Init dim baud rate as longword dim inverted as byte as byte 2 error requested baud rate is too low 1 error requested baud rate is too high 0 successfull initialization Configures and initializes the software UART module Parameters baud rate baud rate to be set Maximum baud rate depends on the MCU s clock and working conditions inverted inverted output flag When set to a non zero value inverted logic on output is used Software UART routines use Delay Cyc routine If requested baud rate is too low then calculated parameter for calling Delay Cyc exceeeds Delay Cyc argu ment range If requested baud rate is too high then rounding error of Delay Cyc argument corrupts Software UART timings Global variables Soft UART Rx Pin Receiver pin Soft UART Tx Pin Transmiter pin Soft UART Rx Pin Direction Direction of the Receiver pin Soft UART Tx Pin Direction Direction of the Transmiter pin must be defined before using this function Soft UART connections dim Soft UART Rx Pin as sbit at PIND BO dim Soft UART Tx Pin as sbit at PORTD B1 dim Soft UART Rx Pin Direction as sbit at DDRD BO dim Soft UART Tx Pin Direction sbit at 1 Soft UART connections Initialize Software UART communication on pins Rx Tx at 9600 bps Soft UART Init 9600 0 352 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries S
164. Libraries Man Break Man Receive is blocking routine and it can block the program flow Call this routine from interrupt to unblock the program execution This mechanism is sim ilar to WDT Description Note Interrupts should be disabled before using Manchester routines again see note at the top of this page dim datal error counter as byte sub procedure Timer0Overflow ISR org 0x12 counter 0 if counter gt 20 then Man Break counter 0 reset counter else Inc counter increment counter end if end sub main bit Timer0 overflow interrupt enable TCCRO bit Start timer with 1024 prescaler SREG I bit Interrupt disable Man Receive Init try Man Receive with blocking prevention mechanism SREG I bit 1 Interrupt enable datal Man Receive error SREG I bit 0 Interrupt disable MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 251 CHAPTER 6 Libraries mikroBasic PRO for AVR Library Example The following code is code for the Manchester receiver it shows how to use the Manchester Library for receiving data program Manchester Receiver LC LC dim LCD RS Direction LCD EN Direction LCD D4 Direction LCD D5 Direction LCD D6 Direction LCD D7 Direction as as as as as as PORT POR PORT PORT PORT Lcd module connections dim LCD RS as sbit at LCD EN as sbit at LCD 4 as sbit at D D5 as sbit at LCD
165. MBEDDED WORLD 295 CHAPTER 6 Libraries mikroBasic PRO for AVR Expander Write PortAB 296 sub procedure Expander Write PortAB dim ModuleAddress as byte Prototype dim Data word The function writes word to Port Expander s ports Parameters Besenpusn ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written Data to be written to are passed in Data s higher byte Data to be written to PortB are passed in Data s lower byte Port Expander must be initialized See Expander Init Port Expander s PortA and PortB should be configured as outputs See Expander Set DirectionPortA Expander Set DirectionPortB and Expander Set DirectionPortAB routines Write a byte to Port Expander s PORTA and PORTB Expander Set DirectionPortAB 0 0x0000 set expander s porta and portb to be output Expander Write PortAB 0 55 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Expander Set DirectionPortA sub procedure Expander Set DirectionPortA dim ModuleAddress as byte dim Data as byte Nothing The function sets Port Expander s PortA direction Prototype Parameters Description ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written to the PortA direction register Each bit corresponds to the appr
166. MBEDDED WORLD 477 CHAPTER 6 Libraries mikroBasic PRO for AVR CONVERSIONS LIBRARY mikroBasic PRO for AVR Conversions Library provides routines for numerals to strings and BCD decimal conversions Library Routines You can get text representation of numerical value by passing it to one of the following routines ByteToStr ShortToStr WordToStr IntToStr LongintToStr LongWordToStr FloatToStr The following sub functions convert decimal values to BCD and vice versa Dec2Bcd 20 16 Dec2Bcd16 ByteToStr sub 4 ByteToStr dim input as word dim byref output as string 2 Converts input byte to a string The output string is right justified and remaining positions on the left if any are filled with blanks Prototype Description Parameters input byte to be converted output destination string dim t as word txt as string 2 t 24 ByteToStri t txt r txt is 24 one blank here 478 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries ShortToStr sub 4 ShortToStr dim input as short dim byref output as string 3 Converts input short signed byte number to a string The output string is right justified and remaining positions on the left if any are filled with blanks Prototype Description Parameters input Short number to be converted output destination string dim t as short txt
167. MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 117 CHAPTER 5 Language Reference mikroBasic PRO for AVR PUNCTUATORS The mikroBasic PRO punctuators also known as separators are Brackets Parentheses Comma Colon 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 precedence if z then Useful with conditional statements Eunet Function call no arguments sub function func2 dim n as word Function declaration w parameters For more information refer to Operators Precedence and Associativity Expressions or Functions and Procedures Comma Comma separates the arguments in function calls Led Out l Ly txt Furthermore the comma separates identifiers in declarations dim i j k as word The comma also separates elements in initialization lists of constant arrays const MONTHS as byte 12 51 29 31 30 31 30 31 31 30 31 30 931 118 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference Colon Colon is used to indicate a labeled statement Start nop m goto start For more
168. NS FOR EMBEDDED WORLD 163 CHAPTER 5 Language Reference mikroBasic PRO for AVR DIRECTIVES Directives are words of special significance which provide additional functionality regarding compilation and output The following directives are at your disposal Compiler directives for conditional compilation Linker directives for object distribution in memory COMPILER DIRECTIVES Any line in source code with leading is taken as a compiler directive The initial can be preceded or followed by whitespace excluding new lines The compiler directives are not case sensitive You can use conditional compilation to select particular sections of code to compile while excluding other sections All compiler directives must be completed in the source file in which they begun Directives ZDEFINE and ZUNDEFINE Use directive DEFINE to define a conditional compiler constant flag You can use any identifier for a flag with no limitations No conflicts with program identifiers are possible because the flags have a separate name space Only one flag can be set per directive For example DEFINE extended format Use UNDEFINE to undefine clear previously defined flag Directives IFDEF ELSEIF and ELSE Conditional compilation is carried out by the 1FDEF directive 1FDEF tests whether a flag is currently defined or not i e whether the previous DEFINE directive has been processed for that
169. O for AVR T6963C Box sub procedure T6963C Box dim x0 y0 1 yl as integer dim pcol or as byte Prototype Draws a box on Glcd Parameters Description 0 x coordinate of the upper left box corner y0 y coordinate of the upper left box corner x1 X coordinate of the lower right box corner yl y coordinate of the lower right box corner pcolor color parameter Valid values T6963C BLACK and T6963C WHITE Toshiba module needs to be initialized See the T6963C Init routine Example nus zu cm roe T6963C Circle sub procedure T6963C Circle dim x y as integer dim r as longint dim pcolor as byte Draws a circle on Glcd Prototype Parameters Description x X coordinate of the circle center y y coordinate of the circle center r radius size pcolor color parameter Valid values 6963 BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C_Init routine Ease cies Circle 120 10 T6963C WHITE 452 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries T6963C Prototype sub procedure 6963 Image const pic as byte Displays bitmap on Glcd Parameters pic image to be displayed Bitmap array can be located in both code and Description RAM memory due to the mikroBasic PRO for AVR pointer to const and pointer to RAM equivalency Use the
170. ONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 387 CHAPTER 6 Libraries mikroBasic PRO for AVR byteToStr remoteHost 3 tmp second dyna 12 tmp 0 dyna 13 tmp 1 dyna 14 tmp 2 dyna 15 add separator then remote host port number WordToStr remotePort tmp dyna 16 tmp 0 dyna 17 tmp 1 dyna 18 tmpf 2 dyna 19 tmp 31 dyna 20 tmpf 4 dyna 21 dyna 22 WordToStr destPort tmp dyna 23 tmp 0 24 tmpf 1 dyna 25 tmpf 2 dyna 26 tmp 3 dyna 27 tmpf 4 dyna 28 rj 29 dyna 30 0 the total length of the request is the length of the dynamic string plus the text of the request len 30 regLength puts the dynamic string into the transmit buffer ptr dyna while ptr lt gt 0 SPI Ethernet putByte ptr ptr ptr 1 then puts the request string converted into upper char into the transmit buffer while reqLength lt gt 0 SPI Ethernet putByte SPI Ethernet getByte reqLength reqLength 1 wend result e l n back to the library with the length of the UDP reply end sub end 388 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection 1 OSCILLATOR vcc MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 389 CHAPTER 6 Libraries mikroBas
171. OR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries PWM 16 BIT LIBRARY CMO module is available with a number of AVR MCUs mikroBasic PRO for AVR provides library which simplifies using PWM HW Module Note For better understanding of PWM module it would be best to start with the example provided in Examples folder of our mikroBasic PRO for AVR compiler When you select a MCU mikroBasic PRO for AVR automaticaly loads the correct PWM 16bit library which can be verified by looking at the Library Manager PWM library handles and initializes the PWM module on the given AVR MCU but it is up to user to set the correct pins as PWM output this topic will be covered later in this section Library Routines PWM16bit Init PWM16bit Change Duty PWMt6bit Start PWMt6bit Stop MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 317 CHAPTER 6 Libraries mikroBasic PRO for AVR Predefined constants used in PWM 16bit library The following variables are used in PWM 16bit library functions etenim eni e Selects the Timer Counter1 with PWMh6bit Start and PWM16bit Stop Selects the Timer Counter3 used with PWM16bit_Start and PWM16bit Stop Selects the channel A on Timer Counter1 used with PWMn16bit Change Duty MEN CHE Selects the channel on Timer Counter1 used with U
172. PHSEG2 PRG ON and d with CANSPIInit CANSPI CONFIG XTD MSG and CANSPI CONFIG DBL BUFFER ON and CANSPI CONFIG VALID XTD MSG and CANSPI CONFIG LINE FILTER OFF spri Init initialize SPI1 module Spi Rd Ptr GSPII Read Pass pointer to SPI Read sub function of used SPI module CANSPIImi it alize 1 3 32 92 1 C0am Init Flags itialize external CANSPI module PISetOperationMode CANSPI MODE CONFIG OxFF t CONFIGURATION mode PISetMask CANSPI MASK 1 1 CANSPI CONFIG XTD MSG t all maski bits to ones r Tm S e S e CANSPISetMask CANSPI MASK B2 1 CANSPI CONFIG XTD MSG e S e S CAN o o t all mask2 bits to ones PISetFilter CANSPI FILTER B2 F3 12111 CANSPI CONFIG XTD MSG set id of filter Bl FI to 3 PISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode Ix ID 3 set tx ID o MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 187 CHAPTER 6 Libraries mikroBasic PRO for AVR while TRUE endless loop Msg Rcvd CANSPIRead Rx ID RxTx Data Rx Data Len Can Rcv Flags receive message if Rx ID 12111 and Msg Rcvd then if message received check id PORTO RxTx Data 0 id correct output data FORTC Inc RxTx Dataf 0 increment received data CANSPIWrite Tx ID RxTx Data 1 Can Send Flags send incremented data back end if wend end HW Connection voc 100K Q
173. Pass pointer to SPI Read Expander J SPI2 Init Advanced SPI MASTER PCY DIVA SPI CLK HI TRAILING Initialize SPI Toshiba 240x128 SPL T6963C Config 240 128 8 0 2 Ly Oy 4 Delay ms 1000 Enable both graphics and text display at the same time SPI T6963C graphics 1 SPI T6963C text 1 panel 0 i 0 curs 0 0 cposy 0 Tv Text messages SPI T6963C write text txt 0 0 SPI T6963C ROM MODE XOR SPI T6963C write text txtl 0 15 SPI T6963C ROM MODE i OE Se bi SPI T6963C cursor height 8 8 pixel height SPI T6863C cursor 0 0 move cursor to top left SPI T6963C cursor 0 cursor OEE Draw rectangles Dd SPI T6963C rectangle 0 0 239 127 SPI T6963C WHITE SPI T 6963C rectangle 20 205 S19 1095 SPI T6963C WHITE SPI T6963C rectangle 40 40 199 87 SPI T6963C WHITE SPI T6963C rectangle 60 60 179 67 SPI T6963C WHITE 438 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI T6963C line 0 0 239 127 SPI T6963C WHITE Draw a cross SPI T6963C line 0 127 239 0 SPI T6963C WHITE SPI T6963C 0 0 239 8 SPI T6963C WHITE Draw solid boxes SPI T6963C box 0 119 239 127 SPI T6963C WHITE te Draw circles
174. R 5 mikroBasic PRO for AVR Language Reference 110 Lexical Elements Overview 111 Whitespace 112 Newline Character 112 Whitespace in Strings 112 Comments 422 ena ex EE IRA REESE qe 113 In IPS 113 Token Extraction Example 113 Literals WRN as CR a RUE CO a vec ee e ve ur RR Y HR 114 Integer Literals is sic cese ed bare Ae es 114 Floating Point Literals 114 Character Literals 115 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD IX Table of Contents mikroBasic PRO for AVR String LiteralS 2 menm UE CEDAR GS 115 Keywords foie area cea teat od dol Pate eene aco eae 116 Identifiers gaat DR coe een DA ke eR Re d 117 Case Sensitivity 117 Uniqueness and Scope 117 Identifier Examples 117 PunctUaltolS xy xA RAO URINE UE ee 118 Brackets cae ERE CERRO ARR SOR RR Ce E dw al ak oe d 118 118 COMMA
175. RB 5 End DAC module connections dim value as word sub procedure InitMain DBAU bit Q Set PAO pin as input bit 0 Set 1 pin as input Chip Select 1 Deselect DAC Chip Select Direction 1 Set CS pin as Output Soft Spi Init Uo Initialize SPL end sub DAC increments 0 4095 gt output voltage 0 Vref sub procedure DAC Output dim valueDAC as word dim temp as byte Chap 0 Select DAC chap Send High Byte temp word valueDAC gt gt 8 and 0 0 Store valueDAC 11 8 to temp 3 0 temp temp or 0x30 Define DAC setting see MCP4921 datasheet Soft SPI Write temp Send high byte via Soft SPI Send Low Byte temp valueDAC Store valueDAC 7 0 to temp 7 0 Soft SPI Write temp Send low byte via Soft SPI Chip Select 1 Deselect DAC chip end sub main InitMain Perform main initialization MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 349 CHAPTER 6 Libraries mikroBasic PRO for AVR When program starts DAC gives T the output in the mid range while TRUE Endless loop value 2048 if PINAO bit and value 4095 then If PAO button is pressed Inc value increment value else if 1 bit and value gt 0 then If BAL button is pressed Dec value T decrement value end if end if Send value to DAC chip DAC Output value Slow down key repeat pace Delay ms 1 wend
176. ROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 101 CHAPTER 3 Specifics mikroBasic PRO for AVR 102 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER AVR Specifics Types Efficiency First of all you should know that AVR ALU which performs arithmetic operations is optimized for working with bytes Although mikroBasic PRO for AVR is capable of handling very complex data types AVR may choke on them especially if you are working on some of the older models This can dramatically increase the time need ed for performing even simple operations Universal advice is to use the smallest possible type in every situation It applies to all programming in general and doubly so with microcontrollers Types efficiency is determined by the part of RAM memo ry that is used to store a variable constant 103 CHAPTER 4 8051 Specifics mikroBasic PRO for AVR Nested Calls Limitations There are no Nested Calls Limitations except by RAM size A Nested call repre sents a function call to another function within the function body With each function call the stack increases for the size of the returned address Number of nested calls is equel to the capacity of RAM which is left out after allocation of all variables Important notes There are many different types of derivates so it is necessary to be familiar with characteristics and special features of the microcontroller in you are usin
177. ROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 415 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI Lcd8 Chr sub procedure SPI Lcd8 Chr dim Row as byte dim Column as byte dim Out Char as byte Prints character on Lcd at specified position Both variables and literals can be passed as character Prototype Description Parameters row Writing position row number column Writing position column number out char character to be written Requires Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routines Write character I at row 2 column 3 SPI Lede Chr 2 2 i SPI Lcd8 Chr Cp Prototype sub procedure SPI Lcd8 Chr CP dim Out Char as byte Prints character on Lcd at current cursor position Both variables and literals can be passed as character Description Parameters out char character to be written Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routines Print at current cursor position Write character e at current cursor position SPI Lod8 Chr Cp e 416 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI Lcd8 Cmd Prototype sub procedure SPI Lcd8 Cmd dim out char as byte Sends command to Lcd Parameters Description out char command to be sent Note Predefined constants can be passed to the function see Available SPI Lcd8 C
178. Ra cen RR RUN CR 54 Segment Display Decoder 55 UDP Terminal shee os RR DER ee 56 Graphic Lcd Bitmap Editor 57 Lcd Custom 58 Macro Editor ee REPERTA REX UGG ROSE RR RR 59 ODtORS supeed vede up e PRU TE Doc 60 Code editor eese Ee LE Rec oe ee vue T da eg RT 60 TOOS cene pae eene etie A REC QU s AUR rece OD 60 Output settings s meld RS eds ns die OR RA 61 Regular Expressions 2 62 Introduction des See tox Euer asia x den e RR d 62 Simple matches 62 Escape sequences 62 Character classes i ea gian duo REESE REN Cha e edes 63 Metacharacters 63 Metacharacters Line separators 63 Metacharacters Predefined classes 64 Metacharacters Word boundaries 64 Metacharacters Iterators 65 Metacharacters Alternatives 66 Examples 2 2 i0 000 sce Leda que end dead E YE Re d 66 Metacharacters Subexpressions
179. Read Sector Cf Write Sector Routines for file handling Cf Fat Init Cf Fat QuickFormat Cf Fat Assign Cf Fat Reset Cf Fat Read Cf Fat Rewrite Cf Fat Append Cf Fat Delete Cf Fat Write Cf Fat Set File Date Cf Fat Get File Date Cf Fat Get File Size Cf Fat Get Swap File MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 191 CHAPTER 6 Libraries mikroBasic PRO for AVR 102 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLE Cf Init Prototype Nothing Initializes ports appropriately for communication with CF card Global variables CF Data Port Compact Flash data port CF_RDY Ready signal line WE Write enable signal line CF OE Output enable signal line 1 Chip detect signal line CF CE1 Enable signal line A2 Address pin 2 CF 1 Address pin 1 CF A0 Address 0 CF Data Port direction Direction of the Compact Flash data direction port CF RDY direction Direction of the Ready pin CF WE direction Direction of the Write enable pin CF OE direction Direction of the Output enable pin CF CD1 direction Direction of the Chip detect pin CF CE1 direction Direction of the Chip enable pin CF A2 direction Direction of the Address 2 pin CF 1 direction Direction of the Address 1 pin CF A0 direction Direction of the Address 0 pin must be defined before usi
180. S485 master side START BYTE 02967 0 STOP BYTE 0xA9 10101001 PACKAGE START BYTE 0x96 ADDRESS DATALE DATA1 if exists DATA2 Tf exists DATA3 if exists CRC STOP BYTE 0 9 DATALEN bits bit7 1 MASTER SENDS 0 SLAVE SENDS bit6 1 ADDRESS WAS XORed with 1 IT WAS EQUAL TO STOP BYTE 0 ADDRESS UNCHANGED bit5 0 FIXED bit4 I DATA3 if exists WAS XORed with 1 IT STARI BYTE ox STOP BYTE 0 DATA3 if exists UNCHANGED bit 1 DATA2 if exists WAS XORed with 1 IT START BYTE of STOP BYTE 0 DATA2 if exists UNCHANGED bit2 1 DATA1 if exists WAS XORed with 1 START BYTE or STOP BYTE 0 DATAL if exists UNCHANGED bitlbitO 0 to 3 NUMBER OF DATA BYTES SEND CRC generation crc send datalen address Gro send 0 af send 11 Xf exists ere send 2 if exists cro send send if ere send START BYTE ere send STOP ere sendt NOTE STOP MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD DATALEN 4 0 lt 4 0 gt values can not take the 5 WAS WAS WAS START lt 4 CHAPTER 6 Libraries EQUAL TO EQUAL TO EQUAL TO 337 CHAPTER 6 Libraries mikroBasic PRO for AVR SOFTWARE FC LIBRARY The
181. Save Project As Save active project file with the different name 122 ecent Projects Open recently used project Qd lose Project Close active project Related topics Keyboard shortcuts Project Toolbar Creating New Project Project Manager Project Settings MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 25 CHAPTER 2 Environment 26 mikroBasic PRO for AVR RUN MENU OPTIONS Eh Start Debugger ET Stop Debugger amp Pause Debugger F9 Ctrl F2 F6 Step Into 9 Step Over F F8 Step Out Ctr F8 4 Jump To Interrupt F2 ij Toggle Breakpoint F5 amp Breakpoints Shift F4 Be Clear Breakpoints Shift Ctrl F5 GS Watch Window Shift F5 5 View Stopwatch Disassembly mode Alt D Sh Start Debugger Stop Debugger jj Pause Debugger Step Into 4 Step Over O Step Out 4 Jump To Interrupt amp Toggle Breakpoint Show Hide Breakpoints Ek Clear Breakpoints 6S Watch Window 5 View Stopwatch isassembly mode Description F9 Start Software Simulator CtrltF2 Stop debugger F6 Pause Debugger Step Into Step Over Ctrl F8 Step Out F2 Jump to interrupt in current project F5 Toggle Breakpoint Shift F4 Breakpoints Shift Ctrl F5 Clear Breakpoints Shift F5 Show Hide Watch Window Show Hide Stopwatch Window Ctrl D Toggle
182. Sorte 122 Pin Dire ction as sbit sfr in ction as sbit at external DDRC B1 338 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Library Routines Soft I2C Init Soft I2C Start Soft I2C Read Soft I2C Write Soft I2C Stop Soft 2 Break Soft I2C Init Prototype sub Nothing Configures the software 2 module Global variables Soft I2C Scl Output Soft 2 clock output line Soft I2C Sda Output Soft 2 data output line R Soft I2C Scl Input Soft 12C clock input line equires 2 Soft I2C Sda Input Soft 14C data input line Soft I2C Scl Pin Direction Direction of the Soft 2 clock pin Soft I2C Sda Pin Direction Direction of the Soft 2 data pin must be defined before using this function procedure Soft I2C Init Soft I2C pinout definition Soft I2C Scl Output as sbit at PORTC BO Soft I2C Sda Output as sbit at PORTC B1 Soft I2C Scl Input as sbit at PINC BO Soft I2C Sda Input as sbit at 1 Soft I2C Scl Pin Direction as sbit at DDRC BO Soft I2C Init dim dim dim dim dim dim Soft I2C Sda Pin Direction sbit at DDRC Bl End of Soft I2C pinout definition CHAPTER 6 Libraries MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 339 CHAPTER 6 Libraries mikroBasic PRO for AVR Soft I2C Start Determines if the 12 bus is free and issues START signal Soft
183. T RR uen EORR RS E Oe 358 SOUNG Play exe thus 358 Library 359 HW Connection isset dae bee ied 361 eH LUE e a dde 362 Library RoutineS 362 SPH Init iis soit 10 D aati ae best dae 362 SPM Init Advanced 363 Read eve eda ee a eere ee ae ede a E 364 SPU WING user ee UR NR EIS UE ERE 364 Library 365 HW x iae b baa RR Edd 366 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XIX Table of Contents mikroBasic PRO for AVR SPI Ethernet Library 367 External dependencies of SPI Ethernet Library 368 Library Routines 369 Spi Ethernet a ce eh Re ee ae dene eek ae ves 369 Spi Ethernet Enable 371 Spi Ethernet Disable 372 Spi Ethernet doPacket 374 Spi Ethernet putByte 375 Spi Ethernet putBytes 375 _ _ 51
184. TCP Spi Ethernet UserUDP Spi Ethernet Init Description sub procedure Spi Ethernet Init dim mac as byte dim ip as byte dim fullDuplex as byte Nothing This is MAC module routine It initializes 28 760 controller This function is internaly splited into 2 parts to help linker when coming short of memory ENC28J60 controller settings parameters not mentioned here set to default receive buffer start address 0x0000 receive buffer end address 0 1 transmit buffer start address 0x192r transmit buffer end address 0xirrr RAM buffer read write pointers in auto increment mode receive filters set to default MAC Unicast MAC Broadcast in OR mode flow control with TX and RX pause frames in full duplex mode frames are padded to 60 bytes CRC maximum packet size is set to 1518 Back to Back Inter Packet Gap 0x15 in full duplex mode 0x12 in half duplex mode Non Back to Back Inter Packet Gap 00012 in full duplex mode 0 0 12 in half duplex mode Collision window is set to 63 in half duplex mode to accomodate some ENC28J60 revisions silicon bugs CLKOUT output is disabled to reduce EMI generation half duplex loopback disabled LED configuration default LEDA link status LEDB link activity MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 369 CHAPTER 6 Libraries mikroBasic PRO for AVR Parameters
185. TE DN PWMn16bit Change Duty ud d Selects the channel C on Timer Counter1 used with eoo enum PWMn16bit Change Duty TIMERS DU Selects the channel A on Timer Counter3 used with ae ai PWM16bit_Change_Duty ee Selects the channel B on Timer Counter3 used with Seen ie PWM16bit_Change_Duty TIMERS CH Selects the channel C on Timer Counter3 used with WS PWMh16bit sChange Duty 318 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR CHAPTER 6 Libraries Note Not all of the MCUs have 16bit PWM and not all of the MCUs have both Timer Counter1 and Timer Counter3 Sometimes like its the case with ATmega168 MCU has only Timer Counter1 and channels A and B Therefore constants that have in their name Timer3 or channel C are invalid for ATmega168 and will not be visible from Code Assistant It is highly advisable to use this feature since it handles all the constants available and eliminates any chance of typing error PWMh16bit Init Prototype Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD sub procedure PWM16bit Init dim wave mode as byte dim prescaler as byte dim inverted as byte dim duty as word dim timer as byte Nothing Initializes the PWM module Parameter wave mode is a desired PWM 16bit mode There are several modes included PWM Phase Correct 8 bit PWM Phase Correct 9 bit PWM Phas
186. TIONS FOR EMBEDDED WORLD XV Table of Contents mikroBasic PRO for AVR Man Receive Init 248 Man 249 Man Send Init ice ec Gawain 249 Man Send axes 250 Man Synchro ee EAEE exu ud RES 250 Man Break vss vb KR EE LP BER beta awed debis 251 Library Example dg Bee oka EE EGER ERU REG eid 252 Connection Example 254 Multi Media Card Library 255 Secure Digital Card 255 External dependencies of MMC Library 255 Library RoutineS 256 Mme zx Re EE RUP Sue ied CERE 257 Mmc Read Sector 258 Mmc Write Sector 259 Mmc Read 260 Mme Read Csd iiec ludus Rer eui A e XO bale db ERR 260 Mime ko au eR ORC RR ace UR 261 Mmc Fat QuickFormat 262 Mme Fat 263 Mme Fat Reset osse ver LER CER oe irae dde ea het Rue 264 Mmc Fat 265 Mmc Fat Rewrite 265 Mmc Fat
187. Templates MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 59 CHAPTER 2 Environment mikroBasic PRO for AVR 60 OPTIONS Options menu consists of three tabs Code Editor Tools and Output settings Code editor The Code Editor is advanced text editor fashioned to satisfy needs of professionals Tools The mikroBasic PRO for AVR includes the Tools tab which enables the use of short cuts to external programs like Calculator or Notepad You can set up to 10 different shortcuts by editing ToolO Tool9 Tool Tool File Name Press button to open file dialog Parameters HEX FILE NAME Full path and name of the out Inset Shortcut F11 Clear al fields LUE MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Output settings CHAPTER 2 Environment By modifying Output Settings user can configure the content of the output files You can enable or disable for example generation of ASM and List file Also user can choose optimization level and compiler specific settings which include case sensitivity dynamic link for string literals setting described in mikroBa sic PRO for AVR specifics Build all files as library enables user to use compiled library mc1 on any AVR MCU when this box is checked or for a selected AVR MCU when this box is left
188. UTIONS FOR EMBEDDED WORLD 217 CHAPTER 6 Libraries mikroBasic PRO for AVR GRAPHIC LCD LIBRARY The mikroBasic PRO for AVR provides a library for operating Graphic Lcd 128x64 with commonly used Samsung 5108 5107 controller For creating a custom set of Glcd images use Glcd Bitmap Editor Tool External dependencies of Graphic Lcd Library The following variables must be defined in all projects Description using Graphic Lcd Library dim GLCD DataPort as byte Glcd Data Port dim GLCD DataPort as sfr external byte at PORTC po of the Glcd Data sim Sd DataPort Direction GLCD DataPort Directi as byte sfr external on as byte at DDRC dim GLCD CS1 as sbit sfr Chip Select 1 line m GLCD CS1 as sbit external PORTD B2 dim GLCD CS2 as sbit sfr GLCD CS2 as sbit external Chip Select 2 line PORTD B3 dim GLCD RS as sbit sfr Register select line dim GLCD RS as sbit external 9 at PORTD B4 dim GLCD RW as sbit sfr 2 dim GLCD RW as sbit external Read Write line at PORTD B5 dim GLCD RST as sbit sfr Reset line dim GLCD RST as sbit external at PORTD B6 dim GLCD EN as sbit sfr Enable line im GLCD EN as sbit external i PORTD B7 LCD CS1 Direction as of the Chip sfr external Select 1 pin Direction as DBZ LCD CS2 Direction as Direction of the Chip sfr external Select 2 pin Direction as D B3 i LCD RS Direction as Direction of the Register dim Direction
189. Ud MikroElektronika SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD making t simple 13 E i Htm n im FI Develop your applications quickly and easily with the world s most intuitive mikroBasic PRO for AVR Microcontrollers Highly sophisticated IDE provides the power you need with the simplicity 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 PRO for AVR makes a fast and reliable tool which can satisfy needs of experienced engineers and beginners alike mikroBasic PRO for AVR March 2009 Reader s note DISCLAIMER mikroBasic PRO for AVR and this manual are owned by mikroElektronika and are pro tected by copyright law and international copyright treaty Therefore you should treat this manual like any other copyrighted material e g a book The manual and the compiler may not be copied partially or as a whole without the written consent from the mikroEelk tronika The PDF edition of the manual can be printed for private or local use but not for distribution Modifying the manual or the compiler is strictly prohibited HIGH RISK ACTIVITIES The mikroBasic PRO for AVR compiler is not fault tolerant and is not designed manufac tured or intended for use or resale as on line control equipmen
190. WARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc Fat Get File Date Prototype sub procedure Mmc Fat Get File Date dim byref year as word dim byref month day hours mins as byte Description Reads time date attributes of the currently assigned file Parameters year buffer to store year attribute to Upon function execution year attribute is returned through this parameter nonth buffer to store month attribute to Upon function execution month attribute is returned through this parameter day buffer to store day attribute to Upon function execution day attribute is returned through this parameter hours buffer to store hours attribute to Upon function execution hours attribute is returned through this parameter mins buffer to store minutes attribute to Upon function execution minutes attribute is returned through this parameter MMC SD card and MMC library must be initialized for file operations See Fat Init The file must be previously assigned See Mmc Fat Assign dim year as word month day hours mins as byte main Mmc Fat Get File Date year month day hours mins end MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 269 CHAPTER 6 Libraries mikroBasic PRO for AVR Mmc Fat Get File Size Returns Size of the currently assigned file in bytes This function reads size of the currently assigned file in bytes
191. WARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Soft UART Break Soft UART Read is blocking routine and it can block the program flow Call this routine from interrupt to unblock the program execution This mechanism is sim Description ilar to WDT Note Interrupts should be disabled before using Software UART routines again see note at the top of this page dim datal error counter as byte sub procedure TimerO0Overflow ISR org 0x12 counter 0 if counter 20 then Soft UART Break counter 0 else Inc counter end if end sub reset counter increment counter main TOIEO bit enable TCORO bate prescaler Timer0 overflow interrupt Start timer with 1024 SREG I bit Interrupt disable Soft UART Init 9600 Soft UART Write 0x55 try Soft UART Read with blocking prevention mechanism SREG I bit 1 Interrupt enable datal Soft UART Read amp error SREG I bit 0 Interrupt disable MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 355 CHAPTER 6 Libraries mikroBasic PRO for AVR Library Example This example demonstrates simple data exchange via software UART If MCU is connected to the PC you can test the example from the mikroBasic PRO for AVR USART Terminal Tool program Soft UART Soft UART connections dim Soft UART Rx Pin as at PIND BO Soft VART Tx Pin as sbit at PORTD B1 Soft UART Rx Pin Di
192. WM16 PRESCALER 16bit 8 PWM16 NON INVERTED 255 320 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries PWM16bit Change Duty sub procedure PWM16bit Change Duty dim duty as word dim channel as byte Nothing Changes PWM duty ratio Parameter duty takes values shown on the table below Where 0 is 0 and TOP value is 100 duty ratio Other specific values for duty ratio can be calculated as Percent TOP 100 Timer Counter Mode of TOP Update of TOVn Flag Operation OCRnX at Set on Description PWM Phase Correct 8 bit 0x00FF BOTTOM Prototype PWM Phase Correct 9 bit 0x01FF BOTTOM Requires PWM module must to be initialised PWM 16bit_Init before using q PWM Set Duty function Example lets set duty ratio to PWM16bit Change Duty 300 TIMER1 CH A MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 321 CHAPTER 6 Libraries PWM16bit Start Prototype sub procedure PWMl16bit Start dim timer as byte Starts PWM 16bit module with alredy preset values wave mode prescaler inverted and duty given the PWMY16bit Init Description mikroBasic PRO for AVR MCU must CMO module to use this library PWM16bit_Init must be called Requires tialised lobit Start 16bit Start PWM16bit Stop TIME Timer Counterl TIME Timer Counter3 usi
193. Write Text GLCD LIBRARY DEMO WELCOME T6963C ROM MODE XOR 450 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries T6963C Line sub procedure T6963C Line dim x0 0 xl yl as integer dim Prototype pcolor as byte Draws a line from x0 yO to x1 y1 Parameters Description x0 x coordinate of the line start y0 y coordinate of the line end x1 X coordinate of the line start yl y coordinate of the line end pcolor color parameter Valid values T6963C BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the T6963C Init routine NORGE T6963C Rectangle b dure T6963C Rectangle dim x0 0 x1 yl as integer di Prototype SUM Rectangle dim x0 0 1 yl as integer dim pcolor as byte Draws a rectangle on Glcd Parameters Description x0 x coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner yl y coordinate of the lower right rectangle corner pcolor color parameter Valid values T6963C BLACK and T6963C WHITE Toshiba Glcd module needs to be initialized See the 6963 Init routine Reston Go m ms im sec mm O MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 451 CHAPTER 6 Libraries mikroBasic PR
194. _Init dim msg as byte 20 RS485Master Receive msg 328 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries RS485Master Send Prototvpe sub procedure Rs485Master Send dim byref data buffer as byte 20 yp dim datalen as byte dim slave address as byte Sends message to Slave s Message format can be found at the bottom of this page Description Parameters data buffer data to be sent datalen number of bytes for transmition Valid values 0 3 slave address Slave s address MCU must be initialized as a Master for RS 485 communication See RS485Master Init It is the user s responsibility to ensure by protocol that only one device sends data via 485 bus at a time dim msg as byte 20 send 3 bytes of data to slave with address 0x12 RS485Master Send msg 3 0x12 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 329 CHAPTER 6 Libraries mikroBasic PRO for AVR RS485Slave Init Prototype sub procedure RS485Slave Init dim slave address as byte Initializes MCU as a Slave for RS 485 communication Description Parameters slave address Slave address Global variables R8485 rxtx pin this pin is connected to RE DE input of RS 485 transceiver see schematic at the bottom of this page RE DE signal controls RS 485 transceiver operation mode Valid values 1 for transmitting and 0 for receiving R8485
195. able with SPI work in Master mode The AVR MCU can easily communicate with other devices via SPI A D converters D A converters MAX7219 LTC1290 etc Note Some AVR MCU s have alternative SPI ports which SPI signals can be redirected to by setting or clearing SPIPS SPI Pin Select bit of the MCUCR register Please consult the appro priate datasheet Library Routines SPI Init SPI1 Init Advanced SPI1 Read SPI1 Write SPI Init SPI Init This routine configures and enables SPI module with the following settings master mode 8 bit data transfer most significant bit sent first serial clock low when idle data sampled on leading edge serial clock fosc 4 Description Requires MCU must have SPI module Initialize the SPI module with default settings SPIl Init 362 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI Init Advanced sub procedure SPI1 Init Advanced dim mode div clock and edge as byte Nothing Configures and initializes SPI SPI1 Init Advanced or SPI1 Init needs to be called before using other functions of SPI Library Prototype Parameters mode fcy div and clock and edge determine the work mode for SPI and can have th following values ___ 5 Clock rate select constants Sck Fosc 4 Master mode _SPI_FCY_DIV4 Sck Fosc 16 Master mode OPI FOY DIVL6 Sc
196. address p with the value of word character Dessniphon For parameter p you can use either a numerical value literal variable constant indicating memory address or a dereferenced value of an object for example mystring PORTB strcat Prototype sub procedure strcat dim byref 51 52 as string 100 The function appends the value of string s2 to string s1 and terminates s with Description a null character strchr Prototype strchr dim byref s as string 100 dim ch as byte The function searches the string s for the first occurrence of the character ch The null character terminating s is not included in the search Description The function returns the position index of the first character ch found in s if no matching character was found the function returns 0xrrrr strcmp Prototype sub function strcmp dim byref 51 52 as string 100 as short The function lexicographically compares the contents of the strings s1 and s2 and returns a value indicating their relationship Meaning D ipti sl less than s2 escription 81 equal to s2 51 greater than 52 The value returned by the function is determined by the difference between the values of the first pair of words that differ in the strings being compared MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 491 CHAPTER 6 Libraries mikroBasic PRO for AVR strcpy Prototype sub procedure strcpy dim byref s1 s2
197. al dim CF as sbit E direction sfr external dim CF as sbit Dl direction sfr external dim CF 1 direction as sbit sfr external Address pin 0 Direction of the Ready pin Direction of the Write Enable pin Direction of the Output Enable pin Direction of the Chip Detect pin Direction of the Chip Enable pin dim CF Data Port as byte at PORTD dim Data Port n as byte at DDRD dim CF RDY as sbit at E as sbit at as sbit at _CD1 as sbit at CF 1 as sbit at TB B3 CF A2 as sbit at TB B2 dim CF A1 as sbit at 1 dim CF 0 sbit at PORTB BO dim CF RDY direction as sbit at DDRB B7 dim as sbit CF WE direction at DDRB B6 dim CF C as sbit 1 direction at DDRB B4 dim CF ICEL as sbit at _direction DDRB B3 dim CF A2 direction Direction of the Address 2 dim CF A2 direction as sbit sfr external pin as sbit at DDRB B2 dim CF A1 direction Direction of the Address 1 as sbit sfr external pin dim CF A0 direction Direction of the Address 0 dim cr AO direction as sbit sfr external pin as sbit at DDRB BO 190 dim CF A1 di as sbit at rection DDRB B1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Library Routines Cf Init Cf Detect Cf Enable Cf Disable Cf Read Init Cf Read Byte Cf Write Init Cf Write Byte Cf
198. all opened projects Build and program active project Start programmer and load current HEX file Open assembly code in editor View statistics for current project EM gt MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 21 CHAPTER 2 Environment mikroBasic PRO for AVR Debugger Eb Eh Eh or e Debugger Toolbar comes with following options m Icon Description Start Software Simulator Run Pause debugger gum ge Stop debugger TO Step into e Step over On Step out gt Run to cursor Toggle breakpoint Toggle breakpoints Lr Clear breakpoints ed View watch window View stopwatch window Styles Toolbar Office 2003 Blue v Office 2003 Blue Office 2003 Silver Office 2003 Olive Office XP Chocolate Arctic Silverfox Soft sand Styles toolbar allows you to easily customize your workspace 22 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Tools Toolbar Tools Toolbar comes with following default options CHAPTER 2 Environment Icon Description Eli Run USART Terminal EEPROM A ASCII Chart Seven segment decoder tool The Tools toolbar can easily be customized by adding new tools in Options F12 window Related to
199. am UART dim uart rd as byte main VARTI Init 19200 Initialize UART module at 9600 bps Delay ms 100 Wait for UART module to stabilize while TRUE Endless loop if VARTI Data Ready lt gt 0 then If data is received uart rd VARTI Read i read the received data UART1 Write uart rd d and send data via UART end if wend end HW Connection i CONNECT Receive n MCU TO PC data Rx SERIAL C759 v WM CABLE 7 e CONNECT Da i Send l PC TO MCU Data Tx RS 232 SUB D 9p es Sz 68 UART HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 475 CHAPTER 6 Libraries mikroBasic PRO for AVR BUTTON LIBRARY The Button library contains miscellaneous routines useful for a project development External dependencies of Button Library The following variable must be defined in all projects using Button library Description dim Button Pin as Declares button pins dim Button Pin as sbit sfr external pins sbit at PINB BO euam Tu Declares direction ofthe Button Pin Direction Button Pin Direction as sbit sfr external button pin as sbit at DDRB BO Library Routines Button Button sub function Button dim time ms as byte dim active state as byte as byte 255 if the pin was in the active state for given period 0 otherwise The function eliminates the influence of contact flickerin
200. ame field modify the name of the file you want to save 5 Click the Save button Closing file 1 Make sure that the tab containing the file that you want to close is the active tab 2 Select File Close from the drop down menu or right click the tab of the file that you want to close and select Close option from the context menu 3 If the file has been changed since it was last saved you will be prompted to save your changes Related topics File Menu File Toolbar Project Manager Project Settings MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 75 CHAPTER 2 Environment 76 mikroBasic PRO for AVR CLEAN PROJECT FOLDER Clean Project Folder This menu gives you option to choose which files from your current project you want to delete Files marked in bold can be easily recreated by building a project Other files should be marked for deletion only with a great care because IDE cannot recover them Clean Project Folder Below is the list of all files in the project folder Files in bold are those generated by the compiler and they can be easily recreated when the project is rebuilt Select which files you want to remove from the project folder Please note that selected files will be permanently deleted from your disk if Lcd asm V LCD dbg 7 Lcd dct 4 LCD dit F LCD hex Led log 7 LCD Ist F Led mbas Lcd mbas ini F Led mbpay 4 LCD mbpav callertable txt
201. amount of code generated and speed up its execution The main features are Constant folding All expressions that can be evaluated in the compile time i e are constant are being replaced by their results 3 5 gt 8 Constant propagation When a constant value is being assigned to a certain variable the compiler recog nizes this and replaces the use of the variable by constant in the code that follows as long as the value of a variable remains unchanged Copy propagation The compiler recognizes that two variables have the same value and eliminates one of them further in the code Value numbering The compiler recognizes if two expressions yield the same result and can there fore eliminate the entire computation for one of them Dead code ellimination The code snippets that are not being used elsewhere in the programme do not affect the final result of the application They are automatically removed Stack allocation Temporary registers Stacks are being used more rationally allowing VERY com plex expressions to be evaluated with a minimum stack consumption Local vars optimization No local variables are being used if their result does not affect some of the global or volatile variables Better code generation and local optimization Code generation is more consistent and more attention is payed to implement spe cific solutions for the code building bricks that further reduce output code size MIK
202. an Synchro Man Break The following routines are for the internal use by compiler only Manchester 0 Manchester 1 Manchester Out Man Receive Init Prototype sub function Man Receive Init as word Description 0 ifinitialization and synchronization were successful 1 upon unsuccessful synchronization The function configures Receiver pin and performs synchronization procedure in order to retrieve baud rate out of the incoming signal Note In case of multiple persistent errors on reception the user should call this routine once again or Man Synchro routine to enable synchronization Global variables MANRXPIN Receive line MANRXPIN Direction Direction of the receive pin must be defined before using this function Initialize Receiver dim MANRXPIN as sbit at PINB BO dim MANRXPIN Direction as sbit at DDRB BO Man Receive Init 248 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Man Receive Prototype sub function Man Receive dim byreferror as byte as byte Returns A byte read from the incoming signal The function extracts one byte from incoming signal Parameters Description error error flag If signal format does not match the expected the error flag will be set to non zero To use this function the user must prepare the MCU for receiving See Requires Man Receive Init dim data erro
203. and Shifting operand to the right by n positions is equivalent to divid ing it by 27 BOOLEAN OPERATORS Although mikroBasic PRO for AVR does not support boolean type you have Boolean operators at your disposal for building complex conditional expressions These operators conform to standard Boolean logic and return either TRUE all ones FALSE zero and logical AND or logical OR logical exclusive not logical negation Boolean operators associate from left to right Negation operator not associates from right to left 150 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference EXPRESSIONS An expression is a sequence of operators operands and punctuators that returns a value The primary expressions include literals constants variables and function calls From them using operators more complex expressions can be created Formally expressions are defined recursively subexpressions can be nested up to the limits of memory Expressions are evaluated according to certain conversion grouping associativity and precedence rules that depend on the operators used presence of parentheses and data types of the operands The precedence and associativity of the operators are summarized in Operator Precedence and Associativity The way operands and subexpressions are grouped does not necessarily specify the actual order in whi
204. and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign dim year as word month day hours mins as byte Cf Fat Get File Date year month day hours mins Cf Fat Get File Size Returns Size of the currently assigned file in bytes This function reads size of currently assigned file in bytes CF card and CF library must be initialized for file operations See Cf Fat Init Requires File must be previously assigned See Cf Fat Assign dim my file size as longword my file size Cf Fat Get File Size 202 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR CHAPTER 6 Cf Fat Get Swap File Description sub function Cf Fat Get Swap File dim sectors cnt as longint dim byref filename as stringi 11 dim file attr as byte as longword Number of the start sector for the newly created swap file if there was enough free space on CF card to create file of required size 0 otherwise This function is used to create a swap file of predefined name and size on the CF media If a file with specified name already exists on the media search for consecutive sectors will ignore sectors occupied by this file Therefore it is rec ommended to erase such file if it exists before calling this function If it is not erased and there is still enough space for a new swap file this function will delete it a
205. and or services marks are the property of the respective owners MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Table of Contents CHAPTER 1 CHAPTER 2 CHAPTER 3 CHAPTER 4 CHAPTER 5 CHAPTER 6 Introduction mikroBasic PRO for AVR Environment mikroBasic PRO for AVR Specifics AVR Specifics mikroBasic PRO for AVR Language Reference mikroBasic PRO for AVR Libraries Table of Contents mikroBasic PRO for AVR CHAPTER 1 FOES us dues eR rea e n AER e 2 Where lo E GEAR EE ER FEX 3 mikroElektronika Associates License Statement and Limited Warranty 4 IMPORTANT READ 4 This license statement and limited warranty constitute a legal agree 4 ment License Agreement 4 LIMITED WARRANTY 5 HIGH RISK ACTIVITIES 6 GENERAL PROVISIONS 6 Technical Support 7 How to Register tisna Ue bed cow ebd dedos 8 Who Gets the License Key 8 How to Get License Key 8 After Receving the License Key 10 CHAPTER 2 IDE OvVerVIOW 2255 eei rcp mL ded ES a da d
206. anel T6963C DisplayTxtPanel T6963C SetGrPanel T6963C SetTxtPanel T6963C PanelFill T6963C GrFill T6963C TxtFill T6963C Cursor Height T6963C Graphics T6963C Text T6963C Cursor T6963C Cursor Blink 444 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR T6963C Init Prototype Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 Libraries sub procedure T6963C init dim width height fntW as byte Nothing Initalizes the Graphic Lcd controller Parameters width width of the Glcd panel height height of the Glcd panel ntW font width Display RAM organization The library cuts the RAM into panels a complete panel is one graphics panel followed by a text panel see schematic below Schematic Global variables i T6963C ctr T6963C ctr T6963C ctr T6963C ctr T6963C ctr C6963C ctr 6963 ctr 6963 ctr 6963C dataPort Data Port Control Port wr Write signal Read signal Command Data signal pin Lrst Reset signal pin 06963C dataPort Direction Direction of Data Port C6963C ctr C6963C ctr Port Direction Direction of Control Port wr Direction Direction of Write signal pin rd Direction Direction of Read signal pin lcd Direction Direction of Command Data signal pin
207. ar Prototype 400 Description sub procedure SPI Glcd Write Char dim chrl as byte dim x pos as byte dim page num as byte dim color as byte Nothing Prints character on Glcd Parameters chri character to be written x pos Character starting position on x axis Valid values 0 127 FontWidth page num the number of the page on which character will be written Valid values 0 7 color COlor parameter Valid values 0 2 The parameter color determines the color of the character 0 white 1 black and 2 inverts each dot Note For x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Use the SPI Glcd Set Font to specify the font for display if no font is speci fied then the default 5x8 font supplied with the library will be used Write character C on the position 10 inside the page 2 SPT Gled Write Char C 10 2 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI Glcd Write Text Prototype Description MIKROELEKTRONI sub procedure SPI Glcd Write Text dim byref text as string 40 dim x pos as byte dim page numb as byte dim color as byte Nothing Prints text on Glcd Parameters text text to be written x pos text starting position on x axis page num the number of the page on which text wi
208. aries Mmc Write Sector Prototype sub function Mmc Write Sector dim sector longint dim byref yp data byte 512 as byte 0 if writing was successful 1 ifthere was an error in sending write command 2 if there was an error in writing data rejected The function writes 512 bytes of data to one MMC card sector 4 2 Parameters Description sector MMC SD card sector to be written to dbu f data to be written buffer of minimum 512 bytes in length MMC SD card must be initialized See Mmc Init write to sector 510 of the MMC SD card dim error as word sectorNo as longword dataBuffer as char 512 main sectorNo 510 error Mmc Write Sector sectorNo dataBuffer end MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 259 CHAPTER 6 Libraries mikroBasic PRO for AVR Mmc Read Cid Prototype sub function Mmc Read Cid dim byref data cid as byte 16 as byte 0 if CID register was read successfully 1 if there was an error while reading The function reads 16 byte CID register Description Parameters data cid buffer of minimum 16 bytes in length for storing CID register content MMC SD card must be initialized See Mmc Init dim error as word dataBuffer as 16 main error Mmc Read Cid dataBuffer Mmc Read Csd sub Read Csd dim byref data for registers as Prototype byte 16 as byte 0 if CSD register was
209. ary 2 2 2 65 ee 231 HW Connection 2 22 5 ete ticket eee whee een et 233 Keypad LIDIA ene tet eeu eae ae 234 Library Routines 22 2222422 22 94 4 wed eed 234 Keypad Inlt ates Gee ace 235 Keypad Key Press 235 Keypad Key 235 Library Example eccer kee oder tpe ee ae er d dues 236 HW Connection 239 TIIS o edere ee sen EET Fede 240 External dependencies of Lcd 240 Library atelier 241 Init hae ee 241 QUU sur du he 242 Led Out CD ovata Gob os 242 Led edie aces eher dura adeundi d ebrei 243 eee Ime wx Wee a ERR Td ge 243 Led Gm 244 Available Lcd Commands 244 Library 2 4 1 245 Manchester Code Library 247 External dependencies of Manchester Code Library 247 Library Routines 248 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLU
210. as string 100 The function copies the value of the string 52 to the string 51 and appends a Description null character to the end of s1 strcspn Prototype sub function strcspn dim byref s1 s2 as string 100 as word The function searches the string s1 for any of the characters in the string 52 The function returns the index of the first character located in s1 that matches any character in s2 If the first character in si matches a character in s2 a value of 0 is returned If there are no matching characters in si the length of the string is returned not including the terminating null character Description strlen Prototype sub function strlen dim byref s as string 100 as word The function returns the length in words of the string s The length does not Description include the null terminating character strncat sub procedure strncat dim byref 51 52 as string 100 dim size Prototype us byc The function appends at most size characters from the string 52 to the string 51 Description and terminates si with a null character If 52 is shorter than the size charac ters 52 is copied up to and including the null terminating character 492 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries strncmp sub function strncmp dim byref 51 52 as stringi 100 dim len as Prototype byte as short The function lexicographically compares
211. as stringi 3 t 24 ByteToStrq t txt txt is 24 one blank here WordToStr sub Um WordToStr dim input as word dim byref output as string 4 Converts input word to a string The output string is right justified and the remaining positions on the left if any are filled with blanks Prototype Description Parameters input word to be converted output destination string dim t as word txt as string 4 t 437 WordToStr t CXE Logs Xs 437 two blanks here MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 479 CHAPTER 6 Libraries mikroBasic PRO for AVR IntToStr sub Ee IntToStr dim input as integer dim byref output as string 5 Converts input integer number to a string The output string is right justified and the remaining positions on the left if any are filled with blanks Prototype Description Parameters input integer number to be converted output destination string dim input as integer txt as string 5 y input 4220 TIHETOSEr rnput txt is 4220 LongintToStr sub procedure LongintToStr dim input as longint dim byref output as string 10 Converts input longint number to a string The output string is right justified and the remaining positions on the left if any are filled with blanks Prototype Description Parameters input longint number to be converted output destination string dim input as longint tx
212. as word sub function First a as word b as word as word forward sub function Second c as word as word dim tmp as word tmp First 2 3 result tmp c end sub sub function First a b as word as word result a b end sub main Volume Second 4 end MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 135 CHAPTER 5 Language Reference mikroBasic PRO for AVR TYPES Basic is strictly typed language which means that every variable and constant need to have a strictly defined type known at the time of compilation The type serves to determine correct memory allocation required to interpret the bit patterns found in the object during subsequent accesses in many type checking situations to ensure that illegal assignments are trapped mikroBasic PRO supports many standard predefined and user defined data types including signed and unsigned integers of various sizes arrays strings pointers and structures Type Categories Types can be divided into simple types arrays strings pointers structures 136 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference SIMPLE TYPES Simple types represent types that cannot be divided into more basic elements and are the model for representing elementary data on machine level Basic memory unit in mikroBasic PRO for AVR has 8 bits Here is an overview of simple t
213. at Imit jcc ceed a tte acu 197 Cf_Fat_QuickFormat 197 CFA ASSIGN So ace hain he a wale eh ae Reale aha ad eg ADR eh d 198 CT Fat Reset ss so Ir Ot m RR RR eee 199 CF Fat Read oce Et Ron etr Roper eere ion x 199 Cf_Fat_Rewrite 200 CT Fat Append ser eed daa ee ben als ERR e d 200 Cf Fat Delete 200 sa coe RR e 201 Cf Fat Set _ 201 Cf Fat Get File 202 Cf Fat Get File Size 202 Cf Fat Get File 203 Library Example el e Re RES 205 HW Connection 210 EEPROM Libra 5e EE Xe ERATES NRW Pas 211 Library Roultlnes ua rubea eR eh 211 EEPROM Read decau is an Ga de ay 211 EEPROM 212 Library Example e eces edie a ae ed d doen 213 Flash Memory Library 214 Library Routines 214 FLASH Read Byte 214 FLASH Read Bytes 215
214. atasheet DDD7 bit 1 Set PORTD pin 7 as output pin for the PWM1 according to datasheet PWM Init PWM PHASE CORRECT MODE _PWM PRESCALER 8 PWM NON INVERTED 127 PWM1 Init PWM1 PHASE CORRECT MODE _PWM1 PRESCALER 8 PWM1 NON INVERTED 127 while TRUE Endless loop if PINBO bit lt gt 0 then Detect if PORTE pin 0 is pressed Delay ms 40 Small delay to avoid deboucing effect Ine ourrent duty Increment duty ratio PWM Set Duty current duty Set incremented duty end if if PINBI bit lt gt 0 then Detect if PORTB pin 1 is pressed Delay ms 40 Small delay to avoid deboucing effect Dec current duty Decrement duty ratio PWM Set Duty current duty Set decremented duty ratio end if if PINCO bit lt gt 0 then Detect if PORTC pin 0 is pressed Delay ms 40 Small delay to avoid deboucing effect tne current dutyl Increment duty ratio PWM1 Set Duty current dutyl Set incremented duty end if MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 315 CHAPTER 6 Libraries mikroBasic PRO for AVR if PINCI bit lt gt 0 then Detect if PORTC pin 1 is pressed Delay ms 40 Small delay to avoid deboucing effect Dec current dutyl Decrement duty ratio PWM1 Set Duty current dutyl Set decremented duty ratio end if wend end HW Connection PWM demonstration 316 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS F
215. ates acknowledges an interrupt request by executing a hardware gener ated CALL to the appropriate servicing routine ISRs ISRs are organized in IVT ISR is defined as a standard function but with the org directive afterwards which con nects the function with specific interrupt vector For example org 0x000B is IVT address of Timer Counter 2 Overflow interrupt source of the ATMEGA16 For more information on interrupts and IVT refer to the specific data sheet Function Calls from Interrupt Calling functions from within the interrupt routine is allowed The compiler takes care about the registers being used both in interrupt and in main thread and performs smart context switching between them two saving only the registers that have been used in both threads It is not recommended to use function call from interrupt In case of doing that take care of stack depth sub procedure Interrupt org 0x16 RS485Master Receive dat end sub Most of the MCUs can access interrupt service routines directly but some can not reach interrupt service routines if they are allocated on addresses greater than 2K from the IVT In this case compiler automatically creates Goto table in order to jump to such interrupt service routines 92 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroBasic PRO for AVR Specifics These principles can be explained on the picture below Interrupt Vector Interrupt Vector Table Tab
216. ave to take care of that Also in order to keep backward compatibility with the first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between the file name and extension i e MIKROELETXT gt MIKROELE TXT In this case the last 3 characters of the string are considered to be file extension Description file cre attr file creation and attributs flags Each bit corresponds to the appropriate file attribut O eseon po oor 6 0 4 Device internal use only never found on disk File creation flag If the file does not exist and this flag is set a new file with specified name will be created Note Long File Names LFN are not supported Requires CF card and CF library must be initialized for file operations See Cf Fat Init Exampe create file with archive attribut if it does not already exist Cf Fat Assign MIKRO007 TXT OxAO0 198 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Cf Fat Reset Prototype sub procedure Cf Fat Reset dim byref size as longword Opens currently assigned file for reading Parameters Description size buffer to store file size to After file has been open for reading its size is returned through this parameter CF card and CF library must be initialized for file operations See Cf Fat Init Requires File must be previous
217. axis y axis Y 23517 7 SPI Glcd HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 405 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI LCD LIBRARY The mikroBasic PRO for AVR provides a library for communication with Lcd with HD44780 compliant controllers in 4 bit mode via SPI interface For creating a custom set of Lcd characters use Lcd Custom Character Tool Note The library uses the SPI module for communication The user must initialize the SPI module before using the SPI Lcd Library Note This Library is designed to work with the mikroElektronika s Serial Lcd Adapter Board pinout See schematic at the bottom of this page for details External dependencies of SPI Lcd Library The implementation of SPI Lcd Library routines is based on Port Expander Library routines Prior to calling any of this library routines Spi Rd Ptr needs to be initialized with the appropriate Read routine External dependencies are the same as Port Expander Library external dependencies Library Routines SPI Lcd Config SPI Lcd Out SPI Lcd Out Cp SPI Lcd Chr SPI Lcd Chr Cp SPI Lcd Cmd 406 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI Lcd Config Prototype sub procedure SPI Lcd Config dim DeviceAddress as by
218. ber text text to be written Lcd needs to be initialized for SPI communication see SPI Lcd Config routines Write text Hello on Lcd starting from row 1 column 3 SPI Led Out l 3 Hellol SPI Lcd Out Cp Prototype Description Requires sub procedure SPI Lcd Out CP dim text as string 19 Nothing Prints text on the Lcd at current cursor position Both string variables and liter als can be passed as a text Parameters text text to be written Lcd needs to be initialized for SP communication see SPI Lcd Config routines Write text Here at current cursor position SEI Lcd Out CP Herel 408 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI Lcd Chr Prototvpe sub procedure SPI Lcd Chr dim Row as byte dim Column as byte ype laim out Char as byte Prints character on Lcd at specified position Both variables and literals can be passed as character Parameters Description Row Writing position row number Column Writing position column number Out Char character to be written Lcd needs to be initialized for SPI communication see SPI Lcd Config routines Write character 1 at row 2 3 SPI Led Chr 2 3 Tif SPI Lcd Chr Cp Prototype sub procedure SPI Lcd Chr CP dim Out Char as byte Prints character on Lcd at current cursor position Both variables and literals can be passed a
219. between Basic source and disassembly Related topics Keyboard shortcuts Debug Toolbar MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment TOOLS MENU OPTIONS mE Programmer Fil USART Terminal Ctrl T EEPROM Editor Ascii Chart Seven Segment Convertor LCD Custom Character GLCD Bitmap Editor UDP Terminal A Export Code To HTML af Options F12 Tools Description mn Run mikroElektronika Programmer mE Programmer USART Terminal Ctr T Run USART Terminal EEPROM Editor Run EEPROM Editor A amp scii Chart Run ASCII Chart Ej Seven Segment Convertor Run 7 Segment Display Decoder Generate HTML code suitable for publishing Export Code To HTML source code on the web LCD Custom Character Generate your own custom Lcd characters GLCD Bitmap Editor Generate bitmap pictures for Glcd UDP Terminal UDP communication terminal a Options F12 Open Options window Related topics Keyboard shortcuts Tools Toolbar MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 27 CHAPTER 2 Environment HELP MENU OPTIONS 9 Help F1 Check For Updates mikroElektronika Support Forums mikroElektronika Web Page How To Register About mikroBasic PRO for AVR File Description Open Help File
220. branch based on a certain condition The select case statement consists of selector expression condition and list of possible values The syntax of the select case statement is select case selector case value 1 statements 1 case value n statements n case else default statements end select selector is an expression which should evaluate as integral value values can be literals constants or expressions and statements can be any statements The case else clause is optional First the selector expression condition is evaluated The select case statement then compares it against all available values If the match is found the statements following the match evaluate and the select case statement terminates In case there are multiple matches the first matching statement will be executed If none of the values matches the selector then default statements in the case else clause if there is one are executed Here is a simple example of the select case statement select case operator case x Ww res nl n2 case res nl n2 case res nl n2 case wow res nl n2 case else res 0 ent cnt 1 end select MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference Also you can group values together for a match Simply separate the items by com mas select case reg case 0 opmode 0 case 1 2 3 4 opmode 1 case 5 6 7 o
221. braries Wait for key to be pressed and released while kp 0 kp Keypad Key Click Store key code in kp variable wend Prepare value for output transform key to it s ASCII value select case kp case 10 kp 42 Uncomment this block for keypad4x3 case 11 kp 48 We case 12 kp 35 Vo NEM default kp 48 case 1 kp 49 1 Uncomment this block for keypad4x4 case 2 kp 50 e 2 case 3 kp e 5l 32 case 4 kp 65 case 5 kp 52 4 case 6 kp 53 ES case 7 kp 54 6 case 8 kp 66 case 9 kp 55 10 kp 56 8 case 11 kp 57 9 case 12 kp 67 vou case 13 kp 42 14 kp 48 0 case 15 kp 35 f case 16 kp 68 tm end select if kp lt gt oldstate then Pressed key differs from previous Gn I oldstate kp MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 237 CHAPTER 6 Libraries else Tne Cenk end if Lcd Che 1 10 if cnt 255 then cnt 0 Led Out 2 10 end if WordToStr cnt txt Led Dut 2 10 txt wend end mikroBasic PRO for AVR Pressed key is same as previous Print key ASCII value on Lcd If counter varialble overflow Transform counter value to string Display counter value on Lcd 238 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection
222. can accommodate value Note You cannot omit type if declaring a constant array Here are a few examples const MAX as longint 10000 const MIN 1000 compiler will assume word type const SWITCH n compiler will assume char type const MSG Hello compiler will assume string type const MONTHS as bytel 12 31 28 21 30 31 90 231 31 320 91 30 31 128 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference LABELS Labels serve as targets for the goto and gosub statements Mark the desired state ment with label and colon like this label identifier statement No special declaration of label is necessary in mikroBasic PRO for AVR Name of the label needs to be a valid identifier The labeled statement and goto gosub statement must belong to the same block Hence it is not possible to jump into or out of routine Do not mark more than one statement in a block with the same label Note The label main marks the entry point of a program and must be present in the main module of every project See Program Organization for more information Here is an example of an infinite loop that calls the procedure repeatedly loop Beep goto loop MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 129 CHAPTER 5 Language Reference mikroBasic PRO for AVR SYMBOLS mikroBasic PRO symbols allow you to create simple macros witho
223. ce An effective CANSPI communication speed depends on SPI and certainly is slower than real CAN CANSPI module refers to mikroElektronika s CANSPI Add on board connected to SPI module of MCU Prior to calling any of this library routines Spi Rd Ptr needs to be initialized with the appropriate SPI Read routine 172 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries External dependencies of CANSPI Library The following variables must be defined in all Description projects using CANSPI Library dim CanSpi CS as sbit Chip Select line dim CanSpi_CS as sbit sfr external at PORTB BO dim CanSpi Rst as Reset line dim CanSpi Rst as sbit sfr external sbit at PORTB B2 di z dim CanSpi CS Bit Directi Direction of the Chip Ee Bie as sbit sfr ds on as sbit at DDRB BO external dim dim CanSpi Rst Bit Direct CanSpi Rst Bit Direct i p sot ott Direction of the Reset pin BODL ion as sbit sfr ion as sbit at external DDRB B2 Library Routines CANSPISetOperationMode CANSPIGetOperationMode CANSPIInitialize CANSPISetBaudRate CANSPISetMask CANSPISetFilter CANSPIread CANSPIWrite The following routines are for an internal use by the library only RegsToCANSPIID CANSPIIDToRegs Be sure to check CANSPI constants necessary for using some of the sub functions MIKROELEKTRONIKA SOFTWARE AND
224. ch they are evaluated by mikroBasic PRO for AVR MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 151 CHAPTER 5 Language Reference mikroBasic PRO for AVR STATEMENTS Statements define algorithmic actions within a program Each statement needs to be terminated with a semicolon In the absence of specific jump and selection statements statements are executed sequentially in the order of appearance in the source code The most simple statements are assignments procedure calls and jump statements These can be combined to form loops branches and other structured statements Refer to Assignment Statements Conditional Statements Iteration Statements Loops Jump Statements asm Statement ASSIGNMENT STATEMENTS Assignment statements have the following form variable expression The statement evaluates expression and assigns its value to variable All rules of implicit conversion are applied Variable can be any declared variable or array ele ment and expression can be any expression Do not confuse the assignment with relational operator which tests for equality mikroBasic PRO for AVR will interpret the meaning of the character from the context 152 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference CONDITIONAL STATEMENTS Conditional or selection statements select from alternative courses of action by test i
225. ch vary from country to country mikroElektronika Associates reserves all rights not specifically granted in this statement mikroElektronika Visegradska 1A 11000 Belgrade Europe Phone 381 11 36 28 830 Fax 381 11 36 28 831 Web www mikroe com E mail office mikroe com 6 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroBasic PRO for AVR Introduction TECHNICAL SUPPORT In case you encounter any problem you are welcome to our support forums at www mikroe com forum Here you may also find helpful information hardware tips and practical code snippets Your comments and suggestions on future develop ment of the mikroBasic PRO for AVR are always appreciated feel free to drop a note or two on our Wishlist In our Knowledge Base www mikroe com en kb you can find the answers to Fre quently Asked Questions and solutions to known problems If you can not find the solution to your problem in Knowledge Base then report it to Support Desk www mikroe com en support In this way we can record and track down bugs more efficiently which is in our mutual interest We respond to every bug report and ques tion in a suitable manner ever improving our technical support MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 CHAPTER 1 Introduction mikroBasic PRO for AVR HOW TO REGISTER The latest version of the mikroBasic PRO for AVR is always available for download ing
226. codes Function CANSPISetMask expects one of these as it s argument const CANSPI MASK B1 as byte 0 CANSPI MASK B2 as byte jk CANSPI FILTER The CANSPI FILTER constants define filter codes Functions CANSPISetFilter expects one of these as it s argument 184 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries const CANSPI FILTER B1 F1 as byte CANSPI FILTER Bl F2 as byte CANSPI FILTER B2 1 as byte CANSPI FILTER B2 F2 as byte CANSPI FILTER B2 F3 as byte CANSPI FILTER B2 F4 as byte 6o BS Fe Library Example This is a simple demonstration of CANSPI Library routines usage First node initi ates the communication with the second node by sending some data to its address The second node responds by sending back the data incremented by 1 First node then does the same and sends incremented data back to second node etc Code for the first CANSPI node program Can Spi 1st dim Can Init Flags Can Send Flags Can Rcv Flags as byte can flags Rx Data Len as byte received data length in bytes RxTx Data as bytel 8 can rx tx data buffer Msg Rcvd as byte reception flag Tx ID Rx ID as longint rx and tx ID CANSPI module connections dim CanSpi CS as sbit at PORTB BO CanSpi CS Direction as sbit at DDRB BO CanSpi Rst as sbit at PORTB B2 CanSpi Rst Direction as sbit at DDRB B2 End CANSPI module connections
227. counteeer etc counte 2 3 r matches strings like counteer Or counteeer but not coun teeeer A little explanation about greediness Greedy takes as many as possible non greedy takes as few as possible For example b and applied to string abbbbc return bbbb b returns b returns empty string 5 2 3 returns bb b 2 3 returns bbb MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 65 CHAPTER 2 Environment mikroBasic PRO for AVR Metacharacters Alternatives You can specify a series of alternatives for a pattern using to separate them so that bit bat bot will match any of bit bat or bot in the target string as would b ilaJo t The first alternative includes everything from the last pattern delimiter or the beginning of the pattern up to the first and the last alternative con tains everything from the last to the next pattern delimiter For this reason it s common practice to include alternatives in parentheses to minimize confusion about where they start and end Alternatives are tried from left to right so the first alternative found for which the entire expression matches is the one that is chosen This means that alternatives are not necessarily greedy For example when matching rou rout against routine only the rou part will match as that is the first alternative tried and it successfully matches the target string
228. ct Direction Direction of the Chip Select pin must be defined before using this function The appropriate hardware SPI module must be previously initialized See the SPI1 Init SPI1 Init Advanced routines MMC module connections dim Mmc Chip Select as sbit sfr at PORTB B2 dim Mmc Chip Select Direction as sbit sfr at DDRB B2 MMC module connections error Mmc Init t with OS line at PORTB BZ dim i as byte SPI1 Init Advanced SPI MASTER SPI FCY DIV2 SPI CLK LO LEAD ING Spi Rd Ptr G8SPII Read Pass pointer to SPI Read function of used SPI module i Mme Init MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 257 CHAPTER 6 Libraries mikroBasic PRO for AVR Mmc Read Sector Prototvpe sub function Mmc Read Sector dim sector as longint dim byref yp data as byte 512 as byte 0 if reading was successful 1 if an error occurred The function reads one sector 512 bytes from MMC card Parameters Description sector MMC SD card sector to be read dbu f buffer of minimum 512 bytes in length for data storage MMC SD card must be initialized See Mmc Init read sector 510 of the MMC SD card dim error as word sectorNo as longword dataBuffer as char 512 main SectorNo 510 error Mme Read Sector sectorNo dataBuffer end 258 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libr
229. ct Level Defines 14 files can also be added to project Project level define files enable you to have defines that are visible in all source files in the project One project may contain several 1 files A file must contain one definition per line for example ANALOG DEBUG TEST There are some predefined project level defines See predefined project level defines Related topics Project Manager Project Settings MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 73 CHAPTER 2 Environment mikroBasic PRO for AVR SOURCE FILES Source files containing Basic code should have the extension mbas The list of source files relevant to the application is stored in project file with extension mbpav along with other project information You can compile source files only if they are part of the project Managing Source Files Creating new source file To create a new source file do the following 1 Select File gt New Unit from the drop down menu or press Ctrl N or click the New File Icon from the File Toolbar 2 A new tab will be opened This is a new source file Select File Save from the drop down menu or press Ctrl S or click the Save File Icon W from the File Toolbar and name it as you want If you use the New Project Wizard an empty source file named after the project with extension mbas will be created automatically The mikroBasic PRO for AVR does not require you to have a source fi
230. d 10 48 write data to the assigned 276 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Eccc ES Opens an existing file and rewrites it sub procedure Open File Rewrite filename 7 c Set filename for single file tests Mmc Fat Assign filename 0 Mmc Fat Rewrite for loop 1 to 55 file contents 0 byte loop div 10 48 file contents 1 byte loop mod 10 48 Mmc Fat Write file contents 42 write data to the assigned file next loop end sub mobs Cines Opens an existing file and appends data to it i and alters the date time stamp sub procedure Open File_ Append filename 7 B Mme Fat Assign filename 0 Mme Fat Set File Date 2005 6 21 10 35 0 Mme Fat Prepare file for append file contents for mikroEle ktronika 2007 Prepare file for append file contents 26 10 Mmc Fat Write file contents 27 Write data to assigned file end sub Opens existing file reads data from it and puts it to USART sub procedure Open File Read filename 7 B Mmc Fat Assign filename 0 Mmc Fat Reset size To read file sub ptoce dure returns size of file while size gt 0 Mme Fat Read character UART1 Write character Write data to USART Dec size wend end sub ED Deletes a file If file doesn t exist it will first be created t and
231. d Globals and Constants Accessing Individual Bits Interrupts AVR Pointers Linker Directives Built in Routines Code Optimization 87 CHAPTER 3 Specifics mikroBasic PRO for AVR BASIC STANDARD ISSUES Divergence from the Basic Standard Function recursion is not supported because of no easily usable stack and limited memory AVR Specific Basic Language Exstensions mikroBasic PRO for AVR has additional set of keywords that do not belong to the standard Basic language keywords code data rx register at bct bak SIr Related topics Keywords AVR Specific 88 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroBasic PRO for AVR Specifics PREDEFINED GLOBALS AND CONSTANTS In order to facilitate AVR programming mikroBasic PRO for AVR implements a num ber of predefined globals and constants SFRs and related constants All AVR SFRs are implicitly declared as global variables of volatile word type These identifiers have an external linkage and are visible in the entire project When creating a project the mikroBasic PRO for AVR will include an appropriate mbas file from defs folder containing declarations of available SFRs and con stants such as PORTB ADPCFG etc All identifiers are in upper case identical to nomenclature in the Microchip datasheets For a complete set of predefined globals and constants look for Defs i
232. d routine by double clicking on it Messe Text mBAVE exe DOG pATMEGAL6 MSP Y 4 O11111114 ongian CAPROGRAM FILES MIROELEXTRONIKAIMOR C ASEC PRO FOR AVRYDIAMPLESYOTHERISOUNDI Scund mbar C PROGRAM FLESIMRCELEKTRONIKAIMUXR CEASEC FRO FOR AVR EXAMPLESYOTHERTSOUNDI Sound bas Conpled Successfully Ab Fes Cormoled in 62 m Used RX bytes 27 24 Free RX bytes 516 RAM bytes 0 RAM bytes 1024 bytes 1024 Used ROM bytes 1228 9 Free ROM bytes 13107 Used ROM bytes 1228 9 Free ROM bytes 13107 91 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 41 CHAPTER 2 Environment 42 mikroBasic PRO for AVR PROJECT MANAGER Project Manager is IDE feature which allows users to manage multiple projects Several projects which together make project group may be open at the same time Only one of them may be active at the moment Setting project in active mode is performed by double click on the desired project in the Project Manager Project Manager SES 11171119 14 4 LedBlinking mbpav 4 Sources amp LedBlinking mbas Binaries 7 Project level defines 7j Image Files 4 Output Files 25 LedBlinking hex 25 LedBlinking asm 25 LedBlinking Ist 7j Other Files Following options are available in the Project Manager Icon Description Save project Group Open project gro
233. der Parameters Description ModuleAddress Port Expander hardware address see schematic at the bottom of this page RegAddress Port Expander s internal register address Data data to be written Requires Port Expander must be initialized See Expander Init Example Write a byte to the Port Expander s register Expander Write Byte 0 1 0xFF MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 291 CHAPTER 6 Libraries mikroBasic PRO for AVR Expander Read PortA Prototype sub function Expander Read PortA dim ModuleAddress as byte as byte 292 Description The function reads byte from Port Expander s PortA Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Port Expander must be initialized See Expander Init Port Expander s PortA should be configured as input See Expander Set Direc tionPortA and Expander Set DirectionPortAB routines Read byte from Port Expander s PORTA dim read data as byte Expander Set DirectionPortA 0 0xFF set expander s porta to be input read data Expander Read PortA 0 Expander Read PortB Prototype sub function Expander Read PortB dim ModuleAddress as byte as byte Description The function reads byte from Port Expander s PortB Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Port Expander must be
234. determines the line color O white 1 black and 2 inverts each dot Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Draw a line between dots 0 0 and 20 30 SPI Gled 0 0 20 30 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 395 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI Glcd V Line Prototvpe sub procedure SPI Glcd V Line dim y start as byte dim y end as yp byte dim x pos as byte dim color as byte Draws a vertical line on Glcd Parameters y start y coordinate of the line start Valid values 0 63 y end y coordinate of the line end Valid values 0 63 x pos X coordinate of vertical line Valid values 0 127 color COlor parameter Valid values 0 2 Description Parameter color determines the line color O white 1 black and 2 inverts each dot Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Example Draw a vertical line between dots 10 5 and 10 25 SPI Gled V Line 5 25 10 1 SPI Glcd H Line Prototvpe sub procedure SPI Glcd V Line dim x start as byte dim x end as byte dim y pos as byte dim color as byte Draws a horizontal line on Glcd Parameters x start X coordinate of the line start Valid values 0 127 Description x end x coordinate of the line end Valid values 0 127 y y coordinate of horizontal line Valid values 0 63 color
235. direction direction of the RS 485 Transmit Receive pin must be defined before using this function UART HW module needs to be initialized See UARTx Init RS485 module pinout dim RS485 rxtx pin as sbit at PORTD B2 dim RS485 rxtx pin direction as sbit at DDRD B2 End of RS485 module pinout Pass pointers to UART functions of used UART module VART Wr Ptr UART1 Write UART Rd Ptr QUARTI Read UART Ptr QUARTI Data Ready VART TX Idle Ptr UART1 TX Idle UART1 Init 9600 initialize UART module RS485Master Init intialize MCU as a Master for RS 485 communication MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 327 CHAPTER 6 Libraries mikroBasic PRO for AVR RS485Master Receive sub RS485Master Receive dim byref data buffer as byte 20 Receives messages from Slaves Messages are multi byte so this routine must be called for each byte received Prototype Parameters data buffer 7 byte buffer for storing received data in the following manner 2 21 message content number of message bytes received 1 3 is set to 255 when message is received is set to 255 if error has occurred address of the Slave which sent the message Description The function automatically adjusts data 41 and data 51 upon every received message These flags need to be cleared by software Requires MCU must be initialized as a Master for RS 485 communication See q RS485Master
236. e loop moves program counter to the line with loop condition bottom of the loop continue jumps continue jumps do here here for i while condition continue continue continue continue jumps bana nes here next i wend loop until condition MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 159 CHAPTER 5 Language Reference mikroBasic PRO for AVR 160 EXIT STATEMENT The exit statement allows you to break out of a routine function or procedure It passes the control to the first statement following the routine call Here is a simple example sub procedure Procl dim error as byte we re doing something here if error TRUE then exit end if some code which won t b xecuted if error is true end sub Note If breaking out of a function return value will be the value of the local variable result atthe moment of exit MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference GOTO STATEMENT Use the goto statement to unconditionally jump to a local label for more informa tion refer to Labels The syntax of the goto statement is goto label name This will transfer control to the location of a local label specified by Label name The goto line can come before or after the label Label and goto statement must belong to the same block Hence it is not possible to jump into or out of a procedure or func
237. e n pede Re Ese CR oe ks ero 77 Output Files i i c Deere EROR en 4 77 Assembly View 77 Error Messages 2 4 ULIS bbe bia ERATES e 78 Compiler Error 78 Warning Messages 79 Hint Messages usas Ru wu hu ies addu nid eqs 79 Software Simulator Overview 80 Watch Window ro RR ER 80 Stopwatch Window 82 RAM Window 4 4 83 Software Simulator Options 84 Creating New 2 85 Multiple Library Versions 86 CHAPTER 3 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD VII Table of Contents mikroBasic PRO for AVR Basic Standard Issues 88 Divergence from the Basic 88 Basic Language Exstensions 88 Predefined Globals and Constants 89 SFRs and related constants 89 Math constants 89 Predefined project level defines
238. e It fetches equested number of bytes from ENC28360 RAM starting from given address If value of 0xrrrr is passed as the address parameter the reading will start from current 28 760 read pointer ERDPT location Description Parameters ptr buffer for storing bytes read from xuc28560 RAM addr ENC28760 RAM start address Valid values 0 8192 n number of bytes to be read Ethernet module has to be initialized See Spi Ethernet Init dim buffer as byte 16 Spi Ethernet getBytes buffer 0x100 16 read 16 bytes starting from address 0 100 378 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Spi Ethernet UserTCP sub function Spi Ethernet UserTCP dim remoteHost as byte dim remotePort as word dim localPort as word dim reqgLength as word as word 0 there should not be a reply to the request Length of TCP HTTP reply data field otherwise This is TCP module routine It is internally called by the library The user accesses to the TCP HTTP request by using some of the Spi Ethernet get rou tines The user puts data in the transmit buffer by using some of the Spi Ether net put routines The function must return the length in bytes of the TCP HTTP reply or 0 if there is nothing to transmit If there is no need to reply to the TCP HTTP requests just define this function with return O as a single state ment
239. e Valid values 1 12 day day attribute Valid values 1 31 hours hours attribute Valid values 0 23 mins minutes attribute Valid values 0 59 seconds Seconds attribute Valid values 0 59 CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign File must be open for writing See Cf Fat Rewrite or Cf Fat Append Example Fat Set File Date 2005 9 30 17 41 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 201 CHAPTER 6 Libraries mikroBasic PRO for AVR Cf Fat Get File Date sub procedure Cf Fat Get File Date dim byref year as word dim byref month as byte dim byref day as byte dim byref hours as byte dim byref mins as byte Reads time date attributes of currently assigned file Parameters year buffer to store year attribute to Upon function execution year attribute is returned through this parameter month buffer to store month attribute to Upon function execution month attribute is returned through this parameter day buffer to store day attribute to Upon function execution day attribute is returned through this parameter hours buffer to store hours attribute to Upon function execution hours attribute is returned through this parameter mins buffer to store minutes attribute to Upon function execution minutes attribute is returned through this parameter Description CF card
240. e values from 0 to 63 specify the left side values from 64 to 127 specify the right side Note For side x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized see Glcd Init routine The following two lines are equivalent and both of them select the left side of Glcd Glcd Select Side 0 Gled Seleot Side 10 Glcd Set X Prototype sub procedure Glcd Set X dim x pos as byte Sets x axis position to x pos dots from the left border of Glcd within the select ed side Parameters Description x pos position on x axis Valid values 0 63 Note For side x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized see Glcd Init routine fame CS MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 221 CHAPTER 6 Libraries mikroBasic PRO for AVR Glcd Set Page Prototype sub procedure Glcd Set Page dim page as byte Selects page of the Glcd Parameters Desenpuon page page number Valid values 0 7 Note For side x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized see Glcd Init routine fame eS Glcd Read Data Prototype sub function Glcd Read Data as byte Returns One byte from Glcd memory Reads data from from the current location of Glcd memory and moves to the Description next location Glcd needs
241. e Correct 10 bit Fast PWM 8 bit Fast PWM 9 bit Fast PWM 10 bit Parameter prescaler chooses prescale value N 1 8 64 256 or 1024 some modules support 32 and 128 but for this you will need to check the datasheet for the desired MCU Paremeter inverted is for choosing between inverted and non inverted PWM signal Parameter duty sets duty ratio from 0 to TOP value this value varies on the PWM wave mode selected PWM signal graphs and formulas are shown below FAST MODE fax i o N 1 fowm TOP t Duty Ratio NE 4 y 40 Stowe Gtewm 7t 2tww Btown Non Inverted Inverted 319 CHAPTER 6 Libraries Description mikroBasic PRO for AVR PHASE f fac i o MODE mU 2 N TOP TOP t Duty Ratio L 5tew teu 7 Non Inverted Inverted The variable represents the prescaler factor 1 8 64 256 or 1024 PWM16bit_Init must be called before using other functions from PWM Library You need a CMO on the given MCU that supports PWM 16bit Before calling this routine you must set the output pin for the PWM according to the datasheet DDRB B1 1 set PORTB pin 1 as output for the PWM 16bit This code example is for ATmega168 for different MCU please consult datasheet for the correct pinout of the PWM module or modules Initialize PWM 16bit module PWM16bit Init PWM16 PHASE CORRECT MODE 8BIT P
242. e flags need to be cleared by software Red ulres MCU must be initialized as a Slave for RS 485 communication See q RS485Slave_Init dim msg as byte 5 RS485Slave Read msg MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 331 CHAPTER 6 Libraries mikroBasic PRO for AVR RS485Slave Send Prototvpe sub procedure RS485Slave Send dim byref data buffer as byte 20 yp dim datalen as byte Sends message to Master Message format can be found at the bottom of this page Description Parameters data buffer data to be sent datalen number of bytes for transmition Valid values 0 3 MCU must be initialized as a Slave for RS 485 communication See 54855 Init It is the user s responsibility to ensure by protocol that only one device sends data via 485 bus at a time dim msg as byte 8 send 2 bytes of data to the master RS485Slave Send msg 2 Library Example This is a simple demonstration of RS485 Library routines usage Master sends message to Slave with address 160 and waits for a response The Slave accepts data increments it and sends it back to the Master Master then does the same and sends incre mented data back to Slave etc Master displays received data on PO while error on receive OxAA and number of consecutive unsuccessful retries are displayed on P1 Slave displays received data on PO while error on receive 0xAA is displayed on P1 Hardware configurations i
243. e from Glcd memory ae Reads data from the current location of memory and moves to the next Description iocati n Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Requires Glcd side x axis position and page should be set first See the functions SPI Set Side SPI Set X and SPI Glcd Set Page dim data as byte data SPI Gled Read Data MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 393 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI Glcd Write Data Prototype sub procedure SPI Glcd Write Data dim Ddata as byte Writes one byte to the current location in Glcd memory and moves to the next location Description Parameters Ddata data to be written Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Glcd side x axis position and page should be set first See the functions SPI Set Side SPI Set X and SPI Glcd Set Page dim ddata as byte SPI Glod Write Data ddata SPI Glcd Fill Prototype sub procedure SPI Glcd Fill dim pattern as byte Fills Glcd memory with byte pattern Parameters Description pattern byte to fill Glcd memory with To clear the screen use SPI 11 0 To fill the screen completely use SPI Fill OxFF Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Clear screen
244. e write line dim OW Bit Write as sbit sfr external sbit at PORTB B2 dim OW Bit Direction dim OW Bit Direction as sbit sfr external Direction of the OneWire pin as sbit at DDRB B2 Library Routines Ow Reset Ow Read Ow Write MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 281 CHAPTER 6 Libraries Ow Reset mikroBasic PRO for AVR Prototype sub function Ow Reset as word Description 0 if the device is present 1 if the device is not present Issues OneWire reset signal for DS18x20 Parameters None Devices compliant with the Dallas OneWire protocol Global variables OW Bit Read OneWire read line OW Bit Write OneWire write line OW Bit Direction Direction of the OneWire pin must be defined before using this function OneWire pinout dim OW Bit Read as sbit at PINB B2 dim OW Bit Write as sbit at PORTB B2 dim OW Bit Direction as sbit at DDRB B2 end of OneWire pinout Issue Reset signal on One Wire Bus Ow Reset 282 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Ow Read Returns Data read from an external device over the OneWire bus Reads one byte of data via the OneWire bus Devices compliant with the Dallas OneWire protocol Global variables Requires OW Bit Read OneWire read line OW Bit Write OneWire write line OW Bit Direction Direction of the OneWire
245. eads data from the specified address in Flash memory for MCUs with Flash memory larger than 64kb dim tmp as longword tmp Flash Read 0x0D00 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 215 CHAPTER 6 Libraries mikroBasic PRO for AVR FLASH Read Words for MCUs with 64kb of Flash memory or less sub procedure FLASH Read Words dim address as word dim buffer as word dim NoWords as word Prototype for MCUs with Flash memory larger than 64kb sub procedure FLASH Read Words dim address as longword dim buffer as word dim NoWords as word Pare Reads number of data words defined by NowWords parameter from the specified Description address in Flash memory to varibale pointed by buffer for MCUs with Flash memory larger than 64kb const F ADDRESS as longint 0x200 dim dat buff 32 as word FLASH Read Bytes F ADDRESS dat buff 64 Library Example The example demonstrates simple write to the flash memory for AVR then reads the data and displays it on PORTB and PORTD program Flash MCU test const F ADDRESS as longint 0x200 const data as word 32 Constant table 0x0000 0x0001 0x0002 0x0003 0x0004 0x0005 0x0006 0x0007 0x0008 0x0009 0x000A 0x000B 0x000C 0x000D 0x000E 0x000F 0x0000 0x0100 0x0200 0x0300 0x0400 0x0500 0x0600 0x0700 0x0800 0x0900 0x0A00 0x0B00 0x0C00 0x0D00 0x0E00 0x0F00 rg 0x200 dim counter as byte word as word dat buff as word 32
246. easy communication with other devices via SPI A D converters D A converters MAX7219 LTC1290 etc Library configuration SPI to Master mode Clock value 20 kHz Data sampled at the middle of interval Clock idle state low Data sampled at the middle of interval Data transmitted at low to high edge Note The Software SPI library implements time based activities so interrupts need to be disabled when using it External dependencies of Software SPI Library The following variables must be defined in all projects using Software SPI Library dim Chip Select as Chip select line dim Chip Select as sbit sfr external p sbit at PORTB BO dim SoftSpi SDI as Data In line dim SoftSpi SDI as sbit sfr external sbit at PINB B6 dim SoftSpi SDO as dim SoftSpi SDO as sbit sfr external Data Out line sbit at PORTB B5 dim SoftSpi CLK as dim SoftSpi CLK as Clock line sbit sfr external sbit at PORTB B7 Description Direction of the Chi dors ae Sel ne Chip Select Direction as sbit sfr external elect pin as sbit at DDRB BO dim Direction of the Data In SoftSpi SDI Direction a p NM Direction as sbit sfr external pin as sbit a DRB B6 dim Direction of the Dat t SoftSpi SDO Direction 829 SDO Direction as sbit sfr external pin as sbit at DDRB B5 dim dim SoftSpi Direction Direction of the Clock pin SoftSpi CLK Direction as sbit sfr external as sbit at DDRB B7 346 MIKROELEKTRONIKA
247. edures locations and sizes Procedures Size Window Displays size of each procedure 4 Memory Usage 2 ROM Allocation 4 Procedures Size 50 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Procedures Locations Window Displays how functions are distributed in microcontroller s memory 4 Memory Usage RAM HTML Window Display statistics in default web browser 4 Memory Usage i You can generate statistics in HTML format too It is suitable for printing and for documenting your project Press the button bellow to generate HTML statistics and to open them in the default web browser View HTML statistics MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 51 CHAPTER 2 Environment mikroBasic PRO for AVR INTEGRATED TOOLS USART Terminal The mikroBasic PRO for AVR includes the USART communication terminal for RS232 communication You can launch it from the drop down menu Tools USART Terminal or by clicking the USART Terminal Icon A from Tools toolbar ies Settings Communication Jl 7 i Baud 9600 Append CR Send as typing Stop Bits One Stop pit FE Sendasnumber TES 1 Clear History i E etae i Ext Pp e te 52 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBas
248. egisters Data to be written to the PortA direction register are passed in Direction s higher byte Data to be written to the PortB direction register are passed in Direction s lower byte Each bit corresponds to the appropriate pin of the PortA PortB register Set bit designates corresponding pin as input Cleared bit designates corresponding pin as output Requires Port Expander must be initialized See Expander Init Set Port Expander s PORTA to be output and PORTB to be input Expander Set DirectionPortAB 0 0x00FF Expander_Set_PullUpsPortA Prototype sub procedure Expander Set PullUpsPortA dim ModuleAddress as yp byte dim Data_ as byte The function sets Port Expander s PortA pull up down resistors Description Parameters Description ModulcAddress Port Expander hardware address see schematic at the bottom of this page Data data for choosing pull up down resistors configuration Each bit corresponds to the appropriate pin of the PortA register Set bit enables pull up for corresponding pin Requires Port Expander must be initialized See Expander Init Example Set Port Expander s PORTA pull up resistors Expander Set PullUpsPortA 0 OxFF 298 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Expander Set PullUpsPortB sub procedure Expander Set PullUpsPortB dim ModuleAddress as byte dim Data as byte Nothing The fu
249. els then ro963C graphies 1 6963 text 1 change cursor 0 then then curs no cursor SPI T6963C cursor 0 case 1 SPI SPI 1 blinking cursor ReS63C cursor 1 6963C cursor blink 1 case 2 SPI 7 SPI 2 non blinking cursor 16963 cursor l 6963C cursor bink 0 end select Delay ms 300 end if end if end if end if end if Move cursor even if n Inc cposx if cposx Cposx 0 Inc cposy SPI T6963C txtCols ot visible then if cposy SPI T6963C grHeight SPI T6963C CHARACTER HEIGHT then cposy 0 end if end if SPI 6963 set cursor cposx Delay ms 100 wend end 440 cposy MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries HW Connection 23517 7 9LVOAWLV Toshiba T6963C Graphic LCD 240x128 Contrast Adjustment SPI T6963C Glcd HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 441 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI T6963C GRAPHIC LCD LIBRARY The mikroBasic PRO for AVR provides a library for working with Glcds based TOSHIBA T6963C controller The Toshiba T6963C is a very popular Lcd controller for the use in small graphics modules It is capable of controlling displays with a res olution up to 240x128 Because of its low power and small outline it is mos
250. ends back text end if wend MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 473 CHAPTER 6 Libraries mikroBasic PRO for AVR UARTx Write Prototype Description sub procedure UARTx Write dim TxData as byte The function transmits a byte via the UART module Parameters TxData data to be sent MCU with the UART module The UART module must be initialized before using this routine See UARTXx Init routine dim data as byte data 0 1 UART1 Write data UARTx Write Text sub procedure UARTx Write Text dim byref uart text as stringi 2551 Sends text parameter uart text via UART Text should be zero terminated UART HW module must be initialized and communication established before using this function See UARTXx Init Read text until the sequence OK is received and send back what s been received UART1 Init 4800 initialize UART module Delay ms 100 while TRUE if UART1 Data Ready 1 if data is received UARTI Read Text output delim 10 reads text until delim is found UART1 Write Text output sends back text end if wend 474 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example This example demonstrates simple data exchange via UART If MCU is connected to the PC you can test the example from the mikroBasic PRO for AVR USART Ter minal progr
251. er Valid values 0 63 color COlor parameter Valid values 0 2 The parameter color determines the color of the box fill O white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd Init routine Draw a box between dots 5 15 and 20 40 Gled Bexib 15 205 40 2 sub procedure Glcd Circle dim x center as integer dim y center as integer dim radius as integer dim color as byte Nothing Draws a circle on Glcd Parameters x center X coordinate of the circle center Valid values 0 127 y center y coordinate of the circle center Valid values 0 63 radius radius size color COlor parameter Valid values 0 2 The parameter color determines the color of the circle line 0 white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd Init routine Draw a circle with center in 50 50 and radius 10 Gled 50 102 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 227 CHAPTER 6 Libraries mikroBasic PRO for AVR Glcd Set Font Prototvpe sub procedure Glcd Set Font dim byref const ActiveFont as byte dim FontWidth as byte dim FontHeight as byte dim FontOffs as word Description Requires Nothing Sets font that will be used with Glcd Write Char and Glcd Write Text routines Parameters activeFont font to be set Needs to be formatted as an array of char aFontWidth width of the font charact
252. er d Equals MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroBasic PRO for AVR Specifics Highest Prototype sub function Highest number as longint as byte Returns Returns the highest byte of number bits 24 31 Function returns the highest byte of number Function does not interpret bit pat terns of number it merely returns 8 bits as found in register Description This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Arguments must be variable of scalar type i e Arithmetic Types and Pointers Ox1AC30F4 tmp Highest d Equals 0x01 nc Prototype sub procedure Inc dim byref par as longint Increases parameter par by 1 4 inep 18 now 5 Dec 4 i8 now 3 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 97 CHAPTER 3 Specifics mikroBasic PRO for AVR 98 Delay us Prototype sub procedure Delay us const time in us as longword Creates a software delay in duration of time us microseconds a constant Range of applicable constants depends on the oscillator frequency Description This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Requires Nothing Example betay us 1000 One millisecond pause Delay ms Pr
253. ers in dots aFontHeight height of the font characters in dots aFontOffs number that represents difference between the mikroBasic PRO for AVR character set and regular ASCII set eg if A is 65 in ASCII character and A is 45 in the mikroBasic PRO for AVR character set aFontOffs is 20 Demo fonts supplied with the library have an offset of 32 which means that they start with space The user can use fonts given in the file Lib GLCDFonts mbas file located in the Uses folder or create his own fonts Glcd needs to be initialized see Glcd Init routine Use the custom 5x7 font myfont which starts with space 32 Gled Set Font myfont 5 7 32 228 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Glcd Write Char Prototype sub procedure Glcd Write Char dim chr as byte dim x pos as byte dim page num as byte dim color as byte Description Prints character on the Glcd Parameters chr character to be written x pos Character starting position on x axis Valid values 0 127 FontWidth page num the number of the page on which character will be written Valid values 0 7 color Color parameter Valid values 0 2 The parameter color determines the color of the character 0 white 1 black and 2 inverts each dot Note For x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be init
254. es string unsigned N unsigned matches string unsigned Escape sequences Characters may be specified using a escape sequences matches a newline Vc a tab etc More generally xnn where nn is a string of hexadecimal digits matches the character whose ASCII value is nn If you need wide Unicode character code you can use x nnnn where nnnn one or more hexadecimal digits char with hex code nn Vx nnnn char with hex code nnnn one byte for plain text and two bytes for Unicode tab HT TAB same as x09 newline NL same as x0a r car return CR same as 0 form feed FF same as alarm bell BEL same as x07 e escape ESC same as xib Examples unsigned x20int matches unsigned int note space the middle tunsigned matches unsigned predecessed by tab 62 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Character classes You can specify a character class by enclosing a list of characters in which will match any of the characters from the list If the first character after the is the class matches any character not in the list Examples count aeiou r finds strings countar counter etc but not countbr countcr etc count aeiou r finds strings countbr countcr etc but not countar counter etc
255. ess the button Check All E and all libraries will be selected In case none library is needed in a project press the button Clear All and all libraries will be cleared from the project Only the selected libraries will be linked Library Manager 29 ADC Button C Type V CAN SPI Compact Flash FAT16 Compact Flash Conversions EEPROM F FLASH V Glcd Fonts V Glcd Keypad4x4 Lcd Constants no Manchester Mmc 16 z 3 A One_Wire Port Expander lt 23 2 185485 Software I2C Software SPI F Software Sound SPI Glcd SPI Lcd SPI Lcd8 SPI T6963C T6963C Time Trigonometry TWI 44 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Icon Description p Refresh Library by scanning files in Uses folder Useful when new are added by copying files to Uses folder Rebuild all available libraries Useful when library sources are available and need refreshing Include all available libraries in current project No libraries from the list will be included in current project CEEE CHa Restore library to the state just before last project saving Related topics mikroBasic PRO for AVR Libraries Creating New Library MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED
256. evice datasheet for operation mode codes The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page check whether the CANSPI module is in Normal mode and if it is do something if CANSPIGetOperationMode CANSPI MODE NORMAL then end if 174 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR CHAPTER 6 Libraries CANSPIlinitialize Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD sub procedure CANSPIInitialize dim SJW as byte dim BRP as byte dim PHSEG1 as byte dim PHSEG2 as byte dim PROPSEG as byte dim CAN CONFIG FLAGS as byte Nothing Initializes the CANSPI module Stand Alone CAN controller in the CANSPI module is set to Disable CAN capture Continue CAN operation in Idle mode Do not abort pending transmissions Fcan clock 4 Tcy Fosc Baud rate is set according to given parameters CAN mode Normal Filter and mask registers IDs are set to zero Filter and mask message frame type is set according to cAN CONFIG FLAGS value EG2PHTS WAKFIL and DBEN bits are set according to CONFIG FLAGS value SAM 5 Parameters as defined CAN controller s datasheet as defined in CAN controller s datasheet
257. f number Function does not interpret bit pat terns of number it merely returns 8 bits as found in register Description This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Requires must be variable of scalar type i e Arithmetic Types and Pointers p e Equals OxF4 Prototype sub function Hi number as longint as byte Returns Returns next to the lowest byte of number bits 8 15 Function returns next to the lowest byte of number Function does not interpret bit patterns of number it merely returns 8 bits as found in register Description This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit must be variable of scalar type i e Arithmetic Types and Pointers 0 1 30 4 s Hi d Equals 0x30 Higher Prototype sub function Higher number as longint as byte Returns Returns next to the highest byte of number bits 16 23 Function returns next to the highest byte of number Function does not interpret bit patterns of number it merely returns 8 bits as found in register Description This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Arguments must be variable of scalar type i e Arithmetic Types and Pointers 0 1 30 4 tmp High
258. ffer as byte data This memory specifier allows variable to be stored in the Rx space Register file rx Note In most of the cases there will be enough space left for the user variables Description in the Rx space However since compiler uses Rx space for storing temporary variables it might happen that user variables will be stored in the internal data SRAM when writing complex programs puts y in Rx space dim y as char rx MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 107 CHAPTER 4 8051 Specifics mikroBasic PRO for AVR 108 io Description This memory specifier allows user to access the Memory space put io buff in io memory space dim io buff as byte io sfr This memory specifier in combination with rx data allows user to Description access special function registers It also instructs compiler to maintain same identifier in Basic and assembly dim io buff as byte io sfr put io buff in I O memory space dim y as char rx sfr puts y in Rx space dim temp as byte data sfr and dim temp as byte sfr are equiva lent and put temp in Extended I O Space register If no other memory specifier is used rx io str code Or data regis Description ter specifer places variable in Rx space and instructs compiler to maintain same identifier in C and assembly Example ain y as char register Note If none of the memory specifiers are used when
259. for AVR SOFTWARE SIMULATOR OVERVIEW The Source level Software Simulator is an integral component of the mikroBasic PRO for AVR environment It is designed to simulate operations of the AVR MCUs and assist the users in debugging Basic code written for these devices After you have successfully compiled your project you can run the Software Simu lator by selecting Run Start Debugger from the drop down menu or by clicking the Start Debugger Icon 5h from the Debugger Toolbar Starting the Software Sim ulator makes more options available Step Into Step Over Step Out Run to Cursor etc Line that is to be executed is color highlighted blue by default Note The Software Simulator simulates the program flow and execution of instruc tion lines but it cannot fully emulate AVR device behavior i e it doesn t update timers interrupt flags etc Watch Window The Software Simulator Watch Window is the main Software Simulator window which allows you to monitor program items while simulating your program To show the Watch Window select View Debug Windows Watch from the drop down menu The Watch Window displays variables and registers of the MCU along with their addresses and values There are two ways of adding variable register to the watch list by its real name variable s name in Basic code Just select desired variable register from Select variable from list drop down menu and click the Add Button by
260. for easier project management The Project Manager alows multiple project management General project settings can be made in the Project Settings window Library manager enables simple handling libraries being used in a project The Error Window displays all errors detected during compiling and linking The source level Software Simulator lets you debug executable logic step by step by watching the program flow The New Project Wizard is a fast reliable and easy way to create a project Help files are syntax and context sensitive Like in any modern Windows application you may customize the layout of mikroBasic PRO for AVR to suit your needs best Spell checker underlines identifiers which are unknown to the project In this way it helps the programmer to spot potential problems early much before the project is compiled Spell checker can be disabled by choosing the option in the Preferences dialog F 12 12 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment MAIN MENU OPTIONS Available Main Menu options are pn m m Iz m roject a E ec in IL m Related topics Keyboard shortcuts MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 13 CHAPTER 2 Environment mikroBasic PRO for AVR FILE MENU OPTIONS The File menu is the main entry point for manipulation with the source files Me
261. from our website It is a fully functional software libraries examples and com prehensive help included The only limitation of the free version is that it cannot generate hex output over 2 KB Although it might sound restrictive this margin allows you to develop practical working applications with no thinking of demo limit If you intend to develop really complex projects in the mikroBasic PRO for AVR then you should consider the pos sibility of purchasing the license key Who Gets the License Key Buyers of the mikroBasic PRO for AVR are entitled to the license key After you have completed the payment procedure you have an option of registering your mikroBa sic PRO In this way you can generate hex output without any limitations How to Get License Key After you have completed the payment procedure start the program Select Help How to Register from the drop down menu or click the How To Register Icon 7 Fill out the registration form figure below select your distributor and click the Send button 8 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroBasic PRO for AVR Introduction Step 1 Fill in the form below Please make sure you fill in all required fields Step 2 Make sure that you provided a valid email address in the EMAIL edit box This email will be used for sending you the activation key Step 3 Make sure you select a correct distributor which will make the registra
262. fter allocating new memory space for a new swap file The purpose of the swap file is to make reading and writing to CF media as fast as possible by using the Cf Read Sector and Cf Write Sector functions directly without potentially damaging the FAT system The swap file can be con sidered as a window on the media where the user can freely write read data Its main purpose in the mikroBasic s library is to be used for fast data acquisi tion when the time critical acquisition has finished the data can be re written into a normal file and formatted in the most suitable way Parameters sectors cnt number of consecutive sectors that user wants the swap file to have filename name of the file that should be assigned for file operations The file name should be in DOS 8 3 file name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does not have to take care of that The file name and extension are case insensitive The library will convert them to the proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with the first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between the file name and extension i e MIKROELETXT gt MIKROELE TXT In this case the la
263. function See TWI Init Requires Also START signal needs to be issued in order to use this function See TWI Start Read data and send not acknowledge signal tmp Read 0 TWI Write Sends data byte parameter data via TWI bus TWI must be configured before using this function See TWI Init Also START signal needs to be issued in order to use this function See TWI Start Example Write 0xA3 466 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries TWI Stop Issues STOP signal to TWI operation TWI must be configured before using this function See TWI Init CSCS TWI Status Returns Returns value of status register TWSR the highest 5 bits Emme pues 7 TWI Close Closes TWI connection TWI must be configured before using this function See TWI Init O Library Example This code demonstrates use of TWI Library procedures and functions AVR MCU is connected SCL SDA pins to 24002 EEPROM Program sends data to EEPROM data is written at address 2 Then we read data via TWI from EEPROM and send its value to PORTA to check if the cycle was successful Check the figure below MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 467 CHAPTER 6 Libraries mikroBasic PRO for AVR program TWI Simple main DDRA OxFF configure PORTA as output TWI Init 100000
264. g Some of the AVR MCUs have hardware multiplier Due to this be sure to pay attention when porting code from one MCU to another because compiled code can vary by its size Not all microcontrollers share the same instruction set It is advisable to carefully read the instruction set of the desired MCU before you start writing your code Compiler automatically takes care of appropiate instruction set and if unapropriate asm instruction is used in in line assembly compiler will report an error Program counter size is MCU dependent Thus there are two sets of libraries MCUs with program counter size larger than 16 bits flash memory size larger than 128kb MCUs with program counter size less or equal 16 bits flash memory size smaller than 128kb Assembly SPM instruction and its derivates must reside in Boot Loader section of program memory Part of flash memory can be dedicated to Boot Loader code For details refer to AVR memory organization Related topics mikroBasic PRO for AVR specifics AVR memory organization 104 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 4 mikroBasic PRO for AVR 8051 Specifics AVR MEMORY ORGANIZATION The AVR microcontroller s memory is divided into Program Memory and Data Memory Program Memory ROM is used for permanent saving program being exe cuted while Data Memory RAM is used for temporarily storing and keeping inter mediate results and variab
265. g 111 as byte 0 if MMC SD card was detected successfully formated and initialized 1 if FAT16 format was unseccessful 255 if MMC SD card was not detected Formats to FAT 16 and initializes MMC SD card Parameters mmc fat label volume label 11 characters in length If less than 11 characters are provided the label will be padded with spaces If null string is passed volume will not be labeled Note This routine can be used instead or in conjunction with Mmc Fat Init rou tine Note If MMC SD card already contains a valid boot sector it will remain unchanged except volume label field and only FAT and ROOT tables will be erased Also the new volume label will be set The appropriate hardware SPI module must be previously initialized format and initialize the FAT library if Mmc Fat QuickFormat mikroE 0 then end if MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc Fat Assign Prototvpe sub function Mmc Fat Assign dim byref filename as char 12 dim file cre attr as byte 1 if already exists or file does not exist but a new file is created 0 if file does not exist and no new file is created Assigns file for file operations read write delete All subsequent file opera tions will be applied on an assigned file Parameters filename name of the file that should be assigned for file operation
266. g upon pressing a but ton debouncing The Button pin is tested just after the function call and then again after the debouncing period has expired If the pin was in the active state in both cases then the function returns 255 true Prototype Description Parameters time ms debouncing period in milliseconds active state determines what is considered as active state Valid values 0 logical zero and 1 logical one Global variables Button Pin Button pin line Button Pin Direction Direction of the button pin must be defined before using this function 476 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries PORTC is inverted on every PORTB BO one to zero transition program Button Button connections dim Button Pin as sbit at PINB BO dim Button Pin Direction as sbit at DDRB BO End Button connections dim oldstate as bit Old state flag main Button Pin Direction 0 Set Button pin as input DDRC OxFF Configure PORTC as output PORTC Initial PORTC value oldstate oldstate initial value while TRUE if Bb tton li 1 1 Detect logical one oldstate 1 Update flag end if if oldstate and Button 1 0 then Detect one to zero transition PORTC not PORTC Invert PORTC oldstate 0 Update flag end if wend Endless loop end MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR E
267. ginally it was defined as the beginning of 1970 GMT January 1 1970 Julian day GMT Greenwich Mean Time is a traditional term for the time zone in England The TimeStruct type is a structure type suitable for time and date storage Library Routines Time dateToEpoch Time epochToDate Time datediff Time dateToEpoch sub function Time dateToEpoch dim byref ts as TimeStruct as longint Number of seconds since January 1 1970 OhOOmn00s This function returns the UNIX time number of seconds since January 1 1970 OhOOmn00s Prototype Description Parameters ts time and date value for calculating UNIX time dim tsl as TimeStruct Epoch as longint what is the epoch of the date in ts poch Time dateToEpoch ts1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 495 CHAPTER 6 Libraries mikroBasic PRO for AVR Time epochToDate sub procedure Time epochToDate dim e as longint dim byref ts as Prototype TimeStruct Converts the UNIX time to time and date Description Parameters e UNIX time seconds since UNIX epoch ts time and date structure for storing conversion output dim ts2 as TimeStruct epoch as longint what date is epoch 1234567890 epoch 1234567890 Time epochToDate epoch ts2 Time dateDiff sub function Time dateDiff dim tl as TimeStruct dim t2 as TimeStruct as longint Returns Time difference in seconds as a signed long
268. gs send initial message while TRUE endless loop Msg Revd CANSPIRead Rx ID RxTx Data Rx Data Len Can Rcv Flags receive message if Rx ID 3 and Msg Rcvd then if message received check id PORTC RxTx Data 0 id correct output data at PORTC Inc RxTx Data 0 increment received data Delay ms 10 CANSPIWrite Tx ID RxTx Data dus Can Send Flags send incremented data back end if wend end Code for the second CANSPI node program Can Spi 2nd dim Can Init Flags Can Send Flags Can Rcv Flags as byte can flags Rx Data Len as byte received data length in bytes RxTx Data as byte 8 CAN rx tx data buffer Msg Rcvd as byte reception flag Tx ID Rx ID as longint can rx and tx ID 186 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries CANSPI module connections dim CanSpi CS as sbit at PORTB BO CanSpi CS Direction as sbit at DDRB BO CanSpi Rst as sbit at PORTB B2 CanSpi Rst Direction as sbit at DDRB B2 End CANSPI module connections main PORTC 0 lear PORTC DDRC 255 set PORTC output Can Init Flags 0 Can Send Flags O0 lacs Can Rcv Flags 0 Can Send Flags CANSPI TX PRIORITY and form value to be used CANSPI TX XTD FRAME and with CANSPIWrite CANSPI TX NO RTR FRAME Can Init Flags _CANSPI CONFIG SAMPLE THRICE Form value to be used CANSPI CONFIG
269. gs Show Hide Project Settings window Code Explorer Show Hide Code Explorer window Library Manager Show Hide Library Manager window 1 E Project Manager Shift Ctrl F11 Show Hide Project Manager window Show Hide Bookmarks window Messages Show Hide Error Messages window Macro Editor Show Hide Macro Editor window Show Window List window 18 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR TOOLBARS File Toolbar ea xum File Toolbar is a standard toolbar with following options CHAPTER 2 Environment Icon Opens a new editor window Description oe Open source file for editing or image file for viewing Save changes for active wind Ow Save changes in all opened windows EDI n Close current editor Close all editors lt Print Preview Edit Toolbar 5 Edit Toolbar is standard toolbar with following options Icon Description A Undo last change e td d Redo last change Cut selected text to clipboard Copy selected text to clipboard E B Paste text from clipboard MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 19 CHAPTER 2 Environment mikroBasic PRO for AVR Advanced Edit Toolbar 9 6 93 52 Advanced Edit Toolbar comes with following optio
270. gs as byte CANSPISetOperationMode CANSPI MODE CONFIG set CONFIGURATION mode baud rate settings can contig flags CANSPI CONFIG SAMPLE THRICE and 0 xFF CANSPI module mast config mode for CANSPI CONFIG PHSEG2 P RG ON and CANSPI CONFIG STD MSG CANSPI CONFIG DBL BUFFE n and R ON and CANSPI CONFIG VALID XT D MSG and CANSPI CONFIG LINE FILTER OFF CANSPISetBaudRate l 1 3 3 1 can config flags MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 177 CHAPTER 6 Libraries mikroBasic PRO for AVR CANSPISetMask sub procedure CANSPISetMask dim CAN MASK as byte dim val as longint dim CAN CONFIG FLAGS as byte Nothing Configures mask for advanced filtering of messages The parameter value is bit adjusted to the appropriate mask registers Prototype Parameters CAN MASK CANSPI module mask number Valid values CANSPI MASK constants see CANSPI constants Description vai mask register value CAN CONFIG FLAGS selects type of message to filter Valid values CANSPI CONFIG ALL VALID MSG CANSPI CONFIG MATCH MSG TYPE and CANSPI CONFIG STD MSG CANSPI CONFIG MATCH MSG TYPE and CANSPI CONFIG XTD MSG see CANSPI constants The CANSPI module must be in Config mode otherwise the sub function will be ignored See CANSPISetOperationMode Requires The CANSPI routines are su
271. h bit corresponds to the appropriate network traffic receive filter MAC Broadcast traffic receive filter 0x01 flag When set MAC broadcast i Ethernet BROADCAST traffic will be enabled MAC Multicast traffic receive filter 1 0x02 flag When set MAC multicast traf Ethernet MULTICAST fic will be enabled Lope eee CRC check flag When set pack 5 0x20 ets with invalid field will be i Ethernet CRC discarded Lope ee ELS MAC Unicast traffic receive filter 7 0x80 flag When set MAC unicast traffic 5 1 Ethernet UNICAST will be enabled MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Libraries 371 CHAPTER 6 Libraries Description Requires mikroBasic PRO for AVR Note Advance filtering available in the c285760 module such as Pattern Match Magic Packet and Hash Table can not be enabled by this routine Additionaly all filters except CRC enabled with this routine will work in OR mode which means that packet will be received if any of the enabled filters accepts it Note This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the 28760 module The xxc28560 module should be properly cofigured by the means of Spi Ethernet Init routine Ethernet module has to be initialized See Spi Ethernet Init Spi Ethernet Enable Spi Ethernet CRC or
272. h the request is sent regLength UDP request data field length Note The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply Requires Ethernet module has to be initialized See Spi Ethernet Init This function is internally called by the library and should not be called by the user s code 380 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example This code shows how to use the AVR mini Ethernet library the board will reply to ARP amp ICMP echo requests the board will reply to UDP requests on any port returns the request in upper char with a header made of remote host IP amp port number the board will reply to HTTP requests on port 80 GET method with pathnames will return the HTML main page s will return board status as text string t7 will toggle P3 b0 to P3 b7 bit and return HTML main page all other requests return also HTML main page Main program code include eth enc28j60 utils this is where you should write implemen tation for UDP and HTTP VOkCkCkCkck kck ck ck k ck kck kk kk k ck KKK ck kk AK KK k k KK KK RAM variables dim myMacAddr as byte 6 my MAC address myIpAddr as byte 4 my IP address gwlIpAddr as byte 4 gateway router IP address ipMask as byte 4 network mask for example 255 255 2
273. haracter literal to a string variable String Literals String literal is a sequence of characters from the extended ASCII character set enclosed with quotes Whitespace is preserved in string literals i e parser does not into strings but treats them as single tokens Length of string literal is a number of characters it consists of String is stored inter nally as the given sequence of characters plus a final nuii character This null character is introduced to terminate the string it does not count against the string s total length String literal with nothing in between the quotes null string is stored as a single null character You can assign string literal to a string variable or to an array of char Here are several string literals Hello world Temperature is stable nc uM null string 0 chars long message 12 chars long message 21 chars long two spaces 2 chars long letter 1 char long The quote itself cannot be a part of the string literal i e there is no escape sequence You could use the built in function Chr to print a quote chr 34 Also see String Splicing MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 115 CHAPTER 5 Language Reference KEYWORDS mikroBasic PRO for AVR Keywords are special purpose words which cannot be used as normal identifier names Beside standard BASIC keywords all relevant SFR are defined as global variables and rep
274. has non zero size If MMC SD card has Volume Boot Record i e there is only one logical partition and no MBRs the library works with entire card as a single partition For more information on MBR physical and logical drives primary secondary partitions and partition tables please consult other resources e g Wikipedia and similar Note Before writing operation make sure not to overwrite boot or FAT sector as it could make your card on PC or digital camera unreadable Drive mapping tools such as Winhex can be of great assistance MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 189 CHAPTER 6 Libraries mikroBasic PRO for AVR External dependencies of Compact Flash Library The following variables must be defined in all projects using Compact Flash Library dim CF Data Port as byte sfr external dim CF Data Port Direction as byte sfr external dim CF RDY as sbit sfr external dim CF WE as sbit sfr external dim CF OE as sbit sfr external dim CF CD1 as sbit sfr external dim _ CE1 as sbit sfr external dim CF A2 as sbit i Description Compact Flash Data Port Direction of the Compact Flash Data Port Ready signal line Write Enable signal line Output Enable signal line Chip Detect signal line Chip Enable signal line dim CF 1 as sbit dim CF 0 as sbit sfr external dim CF RDY direction as sbit sfr external dim CF WE direction as sbit sfr extern
275. haves appropriately For special function keys see Special Function Keys Table special is a flag for special function keys F1 Enter Esc etc If key pressed is one of these special will be set to 1 otherwise 0 pressed set to 1 if the key is pressed and 0 if it is released PS 2 keyboard needs to be initialized See Ps2 Config routine dim value special pressed as byte do if Ps2 Key Read value special pressed then if value 13 and special 1 then break end if end if loop until 0 1 304 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Special Function Keys Adapter Board T6369C datasheet 1 2 F5 F6 F7 F8 F9 11 12 Alt porem po 30 po MER NEN poser p p poe ps Ec a a WEN NM EE P fee EE wes EE NK EMEN NN HE NM a a 1 EK WENN MEN NN NE p ce Le pos 1 2 3 4 5 7 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 Libraries MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 305 CHAPTER 6 Libraries mikroBasic PRO for AVR Library Example This simple example reads values of the pressed keys on the PS 2 keyboard and sends them via UART program PS2 Example dim keydata
276. he MMC PORTE loop file contents 0 loop div 10 48 file combents 11 loop mod 10 48 Write tile contents 38 write data to the assigned file UARTl Write next loop end sub Creates many new files and writes data to them sub procedure Create Multiple Files for loop2 B to 2 UART1 Write loop2 this line can slow down the performance filename 7 loop2 set filename Cf Fat Assign filename 0 0 find existing file or cre ate a new one Cf Fat Rewrite To elear file and start with new data for loop 1 to 44 file contents 0 loop div 10 48 file contents 1 loop mod 10 48 Cf Fat Write file contents 38 write data to the assigned file next loop next loop2 end sub oiim CE LE Opens an existing file and rewrites it sub procedure Open File Rewrit 206 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR filename 7 d Cf Fat Assign filename 0 Cf Fat Rewrite for 1 1 to 55 file comtents 0 file contents 1 Cf Fat Write file next loop _ end sub byte loop div 10 byte loop mod 10 contents 38 write Opens an existing file and and alters the date time sub procedure Open File Append filename 7 Cf Fat Assign filename 0 Cf Fat Set File Date 2005 6 21 10 35 0 Cf Fat Append file contents for append file contents 261 10 Cf Fat Write file conten
277. he edge of the IDE To display an auto hidden window move your point er over the tab The window slides back into view and is ready for use 34 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment ADVANCED CODE EDITOR The Code Editor is advanced text editor fashioned to satisfy needs of professionals General code editing is the same as working with any standard text editor including familiar Copy Paste and Undo actions common for Windows environment Advanced Editor Features Adjustable Syntax Highlighting Code Assistant Code Folding Parameter Assistant Code Templates Auto Complete Auto Correct for common typos Spell Checker Bookmarks and Goto Line Comment Uncomment You can configure the Syntax Highlighting Code Templates and Auto Correct from the Editor Settings dialog To access the Settings click Tools Options from the drop down menu click the Show Options Icon at or press F12 key MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 35 CHAPTER 2 Environment mikroBasic PRO for AVR Editor Settings Editor Settings Project Files V Restore Last Opened Project Restore All Opened Files V Save Breakpoints V Save Bookmarks Editor Colors If Opened File Is Externally Modified Prompt for action Reload file but do not prompt Auto Correct Ignore externally made changes
278. he members of a structure by means of dot as a direct member selector If we had declared the variables 1 and 2 of the previously defined type Circle dim circlel circle2 as Circle we could access their individual members like this 7 0 0 circlel radius circlel center Il Ww x circlel center y You can also commit assignments between complex variables if they are of the same type circle2 circlel This will copy values of all members MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference TYPES CONVERSIONS Conversion of variable of one type to variable of another type is typecasting mikroBasic PRO for AVR supports both implicit and explicit conversions for built in types Implicit Conversion Compiler will provide an automatic implicit conversion in the following situations statement requires an expression of particular type according to language definition and we use an expression of different type operator requires an operand of particular type and we use an operand of different type function requires a formal parameter of particular type and we pass it an object of different type result does not match the declared function return type Promotion When operands are of different types implicit conversion promotes the less com plex to the more complex type taking the following steps byte cha
279. he short cut Ctrl G to activate this option Comment Uncomment Also the Code Editor has a feature to comment or uncomment the selected code by sim ple click of a mouse using the Comment Icon 1 Uncomment Icon from the Code Toolbar MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 39 CHAPTER 2 Environment mikroBasic PRO for AVR CODE EXPLORER The Code Explorer gives clear view of each item declared inside the source code You can jump to a declaration of any item by right clicking it Also besides the list of defined and declared objects code explorer displays message about first error and it s location in code Code Explorer Puses 4 main 9 LCD RS 9 LCD EN 9 LCD D4 9 LCD D5 9 LCD D6 9 LCD D7 LCD RS Direction LCD EN Direction CD D4 Direction LCD D5 Direction 9 LCD D6 Direction 9 LCD Direction 9 txt1 9 txt2 9 txt3 9 txt4 Delay Following options are available the Code Explorer Icon Description Ed Expand Collapse all nodes in tree Locate declaration in code 40 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment ROUTINE LIST Routine list diplays list of routines and enables filtering routines by name Routine list window can be accessed by pressing Ctrl L You can jump to a desire
280. hen what do to by default len putConstString httpHeader HTTP header len len putConstString 8httpMimeTypeHTML with HTML MIME type len len putConstString 8indexPage HTML page first part len len putConstString 8indexPage2 HTML page second part end if result e dem return to the library with the number of bytes to transmit end sub vu this sub function is called by the library the user accesses to the UDP request by successive calls to SPI Ethernet getByte the user puts data in the transmit buffer by successive calls to SPI Ethernet putByte the sub function must return the length in bytes of the UDP reply or 0 if nothing to transmit if you don t need to reply to UDP requests just define this sub function with a return 0 as single state ment sub function Spi Ethernet UserUDP dim byref remoteHost byte 4 dim remotePort destPort reqLength as word as word dim len word my reply length ptr as byte pointer to the dynamic buffer tmp as stringi 5 reply is made of the remote host IP address in human readable format byteToStr remoteHost 0 dyna first IP address byte dyna 3 byteToStr remoteHost 1 tmp second dyna 4 tmpf 0 dyna 5 tmpl 1 dyna 6 tmp 2 dyna 7 byteToStr remoteHost 2 tmp second dyna 8 tmp 0 dyna 9 tmpf 1 dyna 10 tmp 2 dyna 11 MIKROELEKTR
281. hen set MAC unicast traffic will be 5 Ethernet UNICAST disabled Note Advance filtering available in the Nc28760 module such as Pattern Match Magic Packet and Hash Table can not be disabled by this routine Note This routine will change receive filter configuration on the fly It will not in any way mess with enabling disabling receive transmit logic or any other part of the 28760 module The 28 760 module should be properly cofigured by the means of Spi Ethernet Init routine Requires Ethernet module has to be initialized See Spi Ethernet Init example Spi Ethernet Disable Spi Ethernet CRC or Spi Ethernet UNICAST disable CRC checking and Unicast traffic MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 373 CHAPTER 6 Libraries mikroBasic PRO for AVR 374 Spi Ethernet doPacket Prototype sub function Spi Ethernet doPacket as byte 0 upon successful packet processing zero packets received or received packet processed successfully 1 upon reception error or receive buffer corruption 28 760 controller needs to be restarted 2 received packet was not sent to us not our IP nor IP broadcast address 3 received IP packet was not IPv4 4 received packet was of type unknown to the library This is MAC module routine It processes next received packet if such exists Packets are processed in the following manner ARP a
282. ialized see Glcd Init routine Use Set Font to speci fy the font for display if no font is specified then default 5x8 font supplied with the library will be used Write character C on the position 10 inside the page 2 cled Write Char C 10 2 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 229 CHAPTER 6 Libraries mikroBasic PRO for AVR Glcd Write Text Prototype Description Glcd Image sub procedure Glcd Write Text dim byref text as string 20 dim X pos as byte dim page num as byte dim color as byte Nothing Prints text on Glcd Parameters text text to be written x pos text starting position on x axis page num the number of the page on which text will be written Valid values 0 7 color color parameter Valid values 0 2 The parameter color determines the color of the text 0 white 1 black and 2 inverts each dot Note For x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized see Glcd Init routine Use Set Font to speci fy the font for display if no font is specified then default 5x8 font supplied with the library will be used Write text Hello world on the position 10 inside the page 2 Gled Write Text Hello world 10 2 1 Prototype sub procedure Glcd Image byref const image byte Description Displays bitmap on Glcd Parameters image
283. ibraries mikroBasic PRO for AVR Library Example The example demonstrates how to communicate with Port Expander 23517 Note that Port Expander pins A2 A1 AO are connected to GND so Port Expander Hardware Address is 0 program PortExpander Port Expander module connections dim SPExpanderRST as sbit at PORTB BO SPExpanderCS sbit at 1 SPExpanderRST Direction as sbit at DDRB BO SPExpanderCS Direction sbit at DDRB B1 End Port Expander module connections dim counter as byte 0 main counter 0 DDRC OxFF Set PORTC as output If Port Expander Library uses SPI1 module SPIL Init Initialize SPI module used with PortExpander Spi Rd Ptr 85 1 Read Pass pointer to SPI Read sub function of used SPI module If Port Expander Library uses SPI2 module 9 SPIZ Inst Initialize SPI module used with PortExpander Spi Rd Ptr SPI2 Read Pass pointer to SPI Read sub function of used SPI module Expander Init 0 Initialize Port Expander Expander Set DirectionPortA 0 0x00 Set Expander s PORTA to be output Expander Set DirectionPortB 0 0xFF Set Expander s PORTB to be input Expander Set PullUpsPortB 0 0xFF Set pull ups to all of the Expander s PORTB pins while TRUE Endless loop Expander Write PortA 0 counter Write i to expander s PORTA Inc counter PORTC Expander Read PortB 0 Read expander s PORTB and write it to LEDs Delay ms
284. ibrary It supports keypads with 1 4 rows and 1 4 columns The code being returned by Keypad Key Click function is in range from 1 16 In this example the code returned is transformed into ASCII codes 0 9 A F and displayed on Lcd In addition a small single byte counter dis plays in the second Lcd row number of key presses program Keypad Test dim kp cnt oldstate as byte txt as 7 Keypad module connections dim keypadPort as byte at PORTB dim keypadPort Direction as byte at DDRB End Keypad module connections Lcd pinout definition dim LCD RS as sbit at PORTD 2 EN as sbit at PORTD 3 LCD D4 as sbit at PORTD 4 5 6 7 LCD D5 sbit at PORTD LCD D6 as sbit at PORTD LCD D7 as sbit at PORTD D D D D dim LCD RS Direction as sbit at DDRD 2 LCD EN Direction as sbit at DDRD 3 LCD 4 Direction as sbit at DDRD 4 LCD D5 Direction as sbit at DDRD 5 LCD D6 Direction as sbit at DDRD 6 LCD D7 Direction as sbit at DDRD 7 end Lcd pinout definitions main oldstate 0 cnt 0 Reset counter Keypad Init Initialize Keypad Led Initialize Lcd Lcd Cmd LCD CLEAR Clear display Lcd Cmd LCD CURSOR OFF Cursor Off Lcd Out 1 1 Key am Write message text on LCD Led Dut 2 JI Tumesi while TRUE kp 0 Reset key code variable 236 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Li
285. ic PRO for AVR SPI GRAPHIC LCD LIBRARY The mikroBasic PRO for AVR provides a library for operating Graphic Lcd 128x64 with commonly used Samsung 5108 5107 controller via SPI interface For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Note The library uses the SPI module for communication User must initialize SPI module before using the SPI Graphic Lcd Library Note This Library is designed to work with the mikroElektronika s Serial Lcd Glcd Adapter Board pinout see schematic at the bottom of this page for details External dependencies of SPI Graphic Lcd Library The implementation of SPI Graphic Lcd Library routines is based on Port Expander Library routines Prior to calling any of this library routines Spi Rd Ptr needs to be initialized with the appropriate SPI Read routine External dependencies are the same as Port Expander Library external dependencies Library Routines Basic routines SPI Glcd Init SPI Glcd Set Side SPI Glcd Set Page SPI Glcd Set X SPI Glcd Read Data SPI Glcd Write Data Advanced routines SPI Glcd Fill SPI Glcd Dot SPI Glcd Line SPI Glcd V Line SPI Glcd H Line SPI Glcd Rectangle SPI Glcd Box SPI Glcd Circle SPI Glcd Set Font SPI Glcd Write Char SPI Glcd Write Text SPI Glcd Image 390 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for CHAPTER 6 AVR Libraries SPI Glcd I
286. ic PRO for AVR Environment ASCII Chart The ASCII Chart is a handy tool particularly useful when working with Lcd display You can launch it from the drop down menu Tools ASCII chart or by clicking the View ASCII Chart Icon 4 from Tools toolbar NUL SOH STX ETX EOT ENQ BEL BS HT LF VT FF 0 1 2 3 4 5 6 7 8 9 10 11 12 DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS 16 7 8 19 20 2 23 24 25 2 28 SPC 32 41 9 2A o an 5 aS eg wih MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 53 CHAPTER 2 Environment mikroBasic PRO for AVR EEPROM Editor The EEPROM Editor is used for manipulating MCU s EEPROM memory You can launch it from the drop down menu Tools EEPROM Editor When Use this EEPROM definition is checked compiler will generate Intel hex file project name ihex that contains data from EEPROM editor When you run mikroElektronika programmer software from mikroBasic PRO for AVR IDE project name nex file will be loaded automatically while ihex file must be loaded manually mem EEPROM Tool 55 PRO M Ed itor Use Eeprom in project Help Device EEPROM Size EEPROM Fill EEPROM File v mies value dem EEPROM Data TTE FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF OFF FF FF FF FF FF FF FF FF FF FF FF FF i
287. id values 0 disable text dispaying and 1 enable text displaying Toshiba Glcd module needs to be initialized See SPI T6963C Config routine enable text displaying SPI T6963C Text 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 435 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI T6963C Cursor Prototype sub procedure SPI T6963C Cursor dim n as byte Nothing 3q Set cursor on off Description Parameters n on off parameter Valid values 0 set cursor off and 1 set cursor on Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set cursor on SPI T6963C Cursor l SPI T6963C Cursor Blink Prototype sub procedure SPI T6963C Cursor Blink dim n as byte Nothing Enable disable cursor blinking E Parameters Description n cursor blinking enable disable parameter Valid values 0 disable cursor blinking and 1 enable cursor blinking Toshiba Glcd module needs to be initialized See SPI 6963 Config routine enable cursor blinking SPI 169636 Cursor Blinkw l Library Example The following drawing demo tests advanced routines of the SPI T6963C library Hardware configurations in this example are made for the T6963C 240x128 display EasyAVR5A board ATmega16 436 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries program SPI T6963C 240x128
288. ies In order to create a library in mikroBasic PRO for AVR follow the steps bellow Create a new Basic source file see Managing Source Files 2 Save the file in one of the subfolders of the compiler s Uses folder LTE64kW or GT64kW see note on the end of the page DriveName Program Files Mikroelektronika mikroBasic PRO for AVR Uses LTE64kW 11 Example mbas Write a code for your library and save it Add Lib Example file in some project see Project Manager Recompile the project If you wish to use this library for all MCUs then you should go to Tools Options Output settings and check Build all files as library box This will build libraries in a common form which will work with all MCUs If this box is not checked then library will be build for selected MCU Bear in mind that compiler will report an error if a library built for specific MCU is used for another one Compiled file Lib Example mci should appear in mikroBasic PRO for AVR Uses LTE64kWw folder Open the definition file for the MCU that you want to use This file is placed in the compiler s Defs folder DriveName Program Files Mikroelektronika mikroBasic PRO for AVR Defs and it is named MCU NAME mlk for example TMEGA216 mlk Add the the following segment of code to lt LIBRARIES gt node of the definition file definition file is in XML format LIB lt ALIAS gt Example Library lt ALIAS g
289. iew statistics of your code Click the Statis Memory Usage Windows Provides overview of RAM and ROM usage in the form of histogram RAM Memory Rx Memory Space Displays Rx memory space usage in form of histogram 72 Memory Usage MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 47 CHAPTER 2 Environment mikroBasic PRO for AVR Data Memory Space Displays Data memory space usage in form of histogram 4 Memory Usage EL 1 015 Free data 9 Used data Special Function Registers Summarizes all Special Function Registers and their addresses 4 Memory Usage 1 4 RAM Special function registers SFR 48 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR General Purpose Registers CHAPTER 2 Environment Summarizes all General Purpose Registers and their addresses Also displays sym bolic names of variables and their addresses General purpose registers GPR 0x62 spitontOffset __Lib_SPIGled_spifontOffset DefDevice amp ddress Lib SPlGlcd DefDevice amp ddress 0x63 spifontw __Lib_SPIGled_spifontw 0x64 spifontH Lib SPlGlcd spifontH 0x65 spifontDef spifontDef 0x67 Spi Rd Ptr Spi Rd Ptr Inaccessible colo FARG SPI H Line 3 Inaccessible loc
290. iler The parser separates tokens from the input stream by creating the longest token possible using the input characters in a left to right scan mikroBasic PRO for AVR recognizes the following kinds of tokens keywords identifiers constants operators punctuators also known as separators Token Extraction Example Here is an example of token extraction See the following code sequence end flag 0 The compiler would parse it into four tokens end flag variable identifier assignment operator 0 newline statement terminator Note that end flag would be parsed as a single identifier rather than the keyword end followed by the identifier flag MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 113 CHAPTER 5 Language Reference mikroBasic PRO for AVR LITERALS Literals are tokens representing fixed numeric or character values The data type of a constant is deduced by the compiler using such clues as numer ic value and format used in the source code Integer Literals Integral values can be represented in decimal hexadecimal or binary notation In decimal notation numerals are represented as a sequence of digits without com mas 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 5 or the prefix ox indicates a hexadecimal numeral for example 8F or 0x8r The
291. in GLCD DataPort Data port Requires LCD CS1 Direction Direction of the Chip select 1 pin LCD CS2 Direction Direction of the Chip select 2 pin LCD RS Direction Direction of the Register select signal pin LCD RW Direction Direction of the Read Write signal pin LCD EN Direction Direction of the Enable signal pin LCD RST Direction Direction of the Reset signal pin LCD DataPort Direction Direction of the Data port must be defined before using this function Glcd module connections dim GLCD DataPort as byte at PORTC GLCD DataPort Direction as byte at DDRC dim GLCD CS1 as sbit at PORTD B2 GLCD CS2 as sbit at PORTD B3 GLCD RS sbit at PORTD B4 GLCD RW sbit at PORTD B5 GLCD EN sbit at PORTD B6 GLCD RST as sbit at PORTD B7 dim GLCD CS1 Direction as sbit at DDRD B2 LCD CS2 Direction as sbit at DDRD B3 LCD RS Direction as sbit at DDRD B4 LCD RW Direction as sbit at DDRD B5 LCD EN Direction as sbit at DDRD B6 LCD RST Direction as sbit at DDRD B7 End Glcd module connections Gled Init 220 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Glcd Set Side Prototype sub procedure Glcd Set Side dim x pos as byte Selects Glcd side Refer to the Glcd datasheet for detailed explaination Parameters x pos position on x axis Valid values 0 127 Description The parameter os specifies the Glcd sid
292. initialized See Expander Init Port Expander s PortB should be configured as input See Expander Set Direc tionPortB and Expander Set DirectionPortAB routines Read a byte from Port Expander s PORTB dim read data as byte Expander Set DirectionPortB 0 0xFF eet expander s portb to be input read data Expander Read PortB 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Expander Read PortAB Prototype sub function Expander Read PortAB dim ModuleAddress as byte as word ores The function reads word from Port Expander s ports PortA readings are in the higher byte of the result PortB readings are in the lower byte of the result Description Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Port Expander must be initialized See Expander Init Port Expander s PortA and PortB should be configured as inputs See Expander Set DirectionPortA Expander Set DirectionPortB and Expander Set DirectionPortAB routines Read a byte from Port Expander s PORTA and PORTB dim read data as word Expander Set DirectionPortAB 0 0xFFFF set expander s porta and portb to be input read data Expander Read PortAB 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 293 CHAPTER 6 Libraries 294 mikroBasic PRO for AVR Expander Write PortA Prototype
293. is graphic panel Description Parameters n graphic panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI 6963 Config routine Example set graphic panel 1 as current graphic panel SPI 6963 SetGrPanel 1 SPI T6963C SetTxtPanel Prototype sub procedure SPI T6963C SetTxtPanel dim n as byte Nothing Compute start address for selected text panel and set appropriate internal point ers All subsequent text operations will be preformed at this text panel Description Parameters n text panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set text panel 1 as current text panel SPI T6963C SetTxtPanelt l MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 433 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI T6963C PanelFill Prototype sub procedure SPI T6963C PanelFill dim v as byte Fill current panel full graphic text with appropriate value 0 to clear Description Parameters v Value to fill panel with Toshiba Glcd module needs to be initialized See SPI T6963C Config routine clear current panel SPI T6963C PanelFill 0 SPI T6963C Prototype sub procedure SPI T6963C GrFill dim v as byte Fill current graphic panel with appropriate value 0 to clear Description Parameters v Value to fill graphic panel with Toshiba Glcd module needs t
294. is metacharacters you can specify number of occurences of previous character metacharacter or subexpression Zero or more greedy similar to 0 one or more greedy similar to 1 Zero or one greedy similar to 0 1 n exactly n times greedy n atleast n times greedy n m atleast n but not more than m times greedy Zero more non greedy similar to 0 one or more non greedy similar to 1 3 Zero or one non greedy similar to 0 1 n exactly n times non greedy n atleast n times non greedy n m atleast n but not more than m times non greedy So digits in curly brackets of the form n m specify the minimum number of times to match the item and the maximum m The form n is equivalent to n n and match es exactly n times The form matches n or more times There is no limit to the size of n or m but large numbers will chew up more memory and slow down execution If a curly bracket occurs in any other context it is treated as a regular character Examples count r R matches strings like counter countelkjdflkj9r and countr count matches strings like counter countelkjdflkj9r but countr count r matches strings like counter countar and countr but not countelkj9r counte 2 r matches string counteer counte 2 r matches strings like counteer counteeer
295. it and SPI1 Init Advanced routines read a byte from the SPI bus dim take dummyl as byte take 5 1 Read dummyl sub procedure 5 1 Write dim wrdata as byte Nothing SPI module must be initialized before using this function See SPI1 Init and SPI1 Init Advanced routines write a byte to the SPI bus dim buffer as byte Writeq burfer 364 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Library Example CHAPTER 6 Libraries The code demonstrates how to use SPI library functions for communication between SPI module of the MCU and Microchip s MCP4921 program SPI DAC module connections dim Chip Select as sbit at PORTB BO Chip Select Direction as sbit at DDRB End DAC module connections dim value as word sub procedure InitMain DDAO bit 0 DDAl bit 0 i Chip Select 1 Chip Select Direction 1 5 1 Init end sub DAC increments 0 4095 gt output volt 12 bit D A converter BO Set PAO pin as input Set PAl pin as input Deselect DAC Set CS pin as Output Initialize SPI1 module age 0 Vref sub procedure DAC Output dim valueDAC as word dim temp as byte Chip Select 0 Send High Byte temp word valueDAC gt gt 8 and 0x0F T temp 3 0 temp temp or 0x30 Define DAC setting 5 1 Write temp Send Low Byte temp valueDAC 5 1 Write temp Send low byte via Store valueDAC 7
296. ithmetic Operators Operator can be used as a prefix unary operator to change sign of a signed value Unary prefix operator can be used but it doesn t affect data For example D g 146 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference RELATIONAL OPERATORS Use relational operators to test equality or inequality of expressions All relational operators return TRUE or FALSE All relational operators associate from left to right Relational Operators in Expressions The equal sign can also be an assignment operator depending on context Precedence of arithmetic and relational operators was designated in such a way to allow complex expressions without parentheses to have expected meaning if aa 5 gt bb 1 0 cc then same as if aa 5 gt bb 1 0 cc then dd My Function end if MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 147 CHAPTER 5 Language Reference mikroBasic PRO for AVR BITWISE OPERATORS Use the bitwise operators to modify the individual bits of numerical operands Bitwise operators associate from left to right The only exception is the bitwise com plement operator not which associates from right to left Bitwise Operators Overview bitwise AND compares pairs of bits and generates a 1 result if both and bits are 1 otherwise it returns 0 ib bitwise inclusive OR com
297. its name ID assembly variable name Simply type name ID of the variable register you want to display into Search the variable by assemby name box and click the Add Button Add Variables can also be removed from the Watch window just select the variable that you want to remove and then click the Remove Button Remove Add All Button _ M Add All adds all variables 80 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Remove Button Remove All removes all variables You can also expand collapse complex variables i e struct type variables strings Values are updated as you go through the simulation Recently changed items are colored red E B E Select variable from list Y FARG_T6963C_circle 4 Peripherals Freeze Name Value Address T6963C cntlrst 0 0094 T6963C grWidth 0 0 0020 0 0009 Cycle 560 00 H Double clicking a variable or clicking the Properties Button Properties opens the Edit Value window in which you can assign a new value to the selected variable register Also you can choose the format of variable register representation between decimal hexadecimal binary float or character All representations except float are unsigned by default For signed representation click the check box next to the Signed label An item s value can be also changed by double clicking item s value field and typi
298. ized with the appropriate UART Read routine Prior to calling any of this library routines UART Ptr needs to be initialized with the appropriate UART_Ready routine Prior to calling any of this library routines TX Idle Ptr needs to be initialized with the appropriate UART TX Idle routine MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 325 CHAPTER 6 Libraries External dependencies of RS 485 Library The following variable must be defined in all projects using RS 485 Library Description Control RS 485 Trans dim RS485 rxtx pin as sbit sfr external mit Receive operation mode dim RS485 rxtx pin direc Direction of the RS 485 tion as sbit sfr Transmit Receive pin external Library Routines 5485 Init 5485 Receive RS485Master Send RS485Slave nit RS485Slave Receive RS485Slave Send mikroBasic PRO for AVR dim RS485 rxtx pin as sbit at PORTD B2 dim RS485 rxtx pin direc tion as sbit at DDRD B2 326 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries RS485Master Init Initializes MCU as a Master for RS 485 communication Global variables R8485 rxtx pin this pin is connected to RE DE input of RS 485 transceiver see schematic at the bottom of this page RE DE signal controls RS 485 transceiver operation mode Requires 85485 rxtx pin
299. ject by clicking Next button New Project Wizard Ime Welcome to the New Project Wizard This wizard helps you e Create a new project e Select the device for your project e Setup device clock and choose device flags e Select desired memory model gt e Add project files Click Next to continue Back Next gt Cancel Step One Select the device from the device drop down list gt 7 New Project Wizard Step 1 5 Select the device you want to use Device Name 5935 x 4 Back Next Cancel MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 69 CHAPTER 2 Environment mikroBasic PRO for AVR Step Two Enter the oscillator frequency value New Project Wizard O a Setup the clock for example 11 0592 MHz Device Clock 11 059200 MHz 4 Back Next Cancel Step Three Specify the location where your project will be saved New Project Wizard Specify where your project will be saved Project File Name D Projects FirstProject FirstProject mbpav 4 Back Next Cancel 70 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Step Four Add project file to the project if they are avaiable at this point You can always add project files later using Project Manager New Project Wizard Step 4 5 8 Add p
300. ject group may be reopend by clicking the Open Project Group Icon All relevant data about the project group is stored the project group file extension ADD REMOVE FILES FROM PROJECT The project can contain the following file types mbas Source files mc1 binary files pld project level defines files image files hex asm and Ist files see output files These files can not be added or removed from project other files T2 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Project Manager 1 55 ee c 4 2 6963 240x128 mbpav 4 17 Sources B T6963C 240x128 mbas amp bitmap mbas 4 17 Binaries bitmap2 mcl Project level defines 4 7j Image Files sample jpg 4 4 Output Files 23 16963 240 128 T6963C 240x128 asm 23 16963 240x128 lst Other Files DATA doc3286 pdf The list of relevant source files is stored in the project file extension mbpav To add source file to the project click the Add File to Project Icon a Each added source file must be self contained i e it must have all necessary definitions after preprocessing To remove file s from the project click the Remove File from Project Icon a Note For inclusion of the module files use the include clause See File Inclusion for more information Project Level Defines Proje
301. k Fosc 64 Master mode SPI FCY DIV64 Description Sck Fosc 128 Master mode SPI FCY DIV128 Sck Fosc 2 Master mode SPI FCY DIV2 Sck Fosc 8 Master mode SPI FCY DIV8 Sck Fosc 32 Master mode SPI DIV32 SPI clock polarity and phase constants Clock idle level is 1 1 Gop T viles d Lii SPI CLK LO LEADING on rising edge eS lock idle level is 1 d pupa TRE IIR Ende ug cue mun SPI CLK LO TRAILING on falling edge Clock idle Level is high sample SPI CLK HI LEADING on rising edge lock idle level is high 1 ads ee Be on falling edge oS Note Some SPI clock speeds are not supported by all AVR MCUs and these are Fosc 2 Fosc 8 Fosc 32 Please consult appropriate datasheet MCU must have SPI module Set SPI to the Master Mode clock Fosc 32 clock idle level is high data sampled on falling edge 5 1 Init Advanced SPI MASTER SPI FCY DIV32 SPI TRAILING MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 363 CHAPTER 6 Libraries SPI1 Read mikroBasic PRO for AVR Prototype sub function 5 1 Read dim buffer as byte as byte Returns Received data Description SPI1 Write Reads one byte from the SPI bus Parameters buffer dummy data for clock generation see device Datasheet for SPI modules implementation details SPI module must be initialized before using this function See SPI1 In
302. le Goto table Direct accessing interrupt service routine and accessing interrupt service routine via Goto table MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 93 CHAPTER 3 Specifics mikroBasic PRO for AVR LINKER DIRECTIVES mikroBasic PRO for AVR uses internal algorithm to distribute objects within memo ry If you need to have a variable or routine at the specific predefined address use the linker directives absolute and org Note You must specify an even address when using the linker directives Directive absolute The directive absolute specifies the starting address in RAM for a variable If the variable spans more than 1 word 16 bit higher words will be stored at the consec utive locations The absolute directive is appended to the declaration of a variable dim x as word absolute 0x32 Variable x will occupy 1 word 16 bits at address 0x32 dim y as longint absolute 0x34 Variable y will occupy 2 words at addresses 0x34 and 0x36 Be careful when using absolute directive as you may overlap two variables by acci dent For example dim 1 as word absolute 0x42 Variable i will occupy 1 word at address 0x42 dim jj as longint absolute 0x40 Variable will occupy 2 words at 0x40 and 0x42 thus changing i changes jj at the same time and vice versa Note You must specify an even address when using the directive absolute Directive org The directive org specifies the s
303. le is corrupted Prior to calling any of this library routines Spi Rd Ptr needs to be initialized with the appropriate SPI Read routine External dependencies of MMC Library The following variable must be defined in all projects using MMC library Description as sbit sfr external as sbit at PINB BO dim dim Mmc Chip Select Direc Direction of the chip select Chip Select Direc tion as sbit sfr in tion as sbit at external DDRB BO MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 255 CHAPTER 6 Libraries mikroBasic PRO for AVR Library Routines Mmc Init Mmc Read Sector Mmc Write Sector Mmc Read Cid Mmc Read Csd Routines for file handling Mmc Fat Init Mmc Fat QuickFormat Mmc Fat Assign Mmc Fat Reset Mmc Fat Read Mmc Fat Rewrite Mmc Fat Append Mmc Fat Delete Mmc Fat Write Mmc Fat Set File Date Mmc Fat Get File Date Mmc Fat Get File Size Mmc Fat Get Swap File 256 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Init Prototype sub function Mmc Init as byte 0 if MMC SD card was detected and successfully initialized 1 otherwise Initializes MMC through hardware SPI interface Description Parameters port Chip select signal port address cspin Chip select pin Global variables Mmc Chip Select Chip Select line Mmc Chip Sele
304. le named the same as the project it s just a mat ter of convenience Opening an existing file 1 Select File gt Open from the drop down menu or press Ctrl O or click the Open File Icon from the File Toolbar In Open Dialog browse to the location of the file that you want to open select it and click the Open button 2 The selected file is displayed in its own tab If the selected file is already open its current Editor tab will become active Printing an open file 1 Make sure that the window containing the file that you want to print is the active window 2 Select File gt Print from the drop down menu or press Ctrl P 3 In the Print Preview Window set a desired layout of the document and click the OK button The file will be printed on the selected printer 74 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Saving file 1 Make sure that the window containing the file that you want to save is the active window 2 Select File gt Save from the drop down menu or press Ctrl S or click the Save File Icon from the File Toolbar Saving file under a different name 1 Make sure that the window containing the file that you want to save is the active window 2 Select File Save As from the drop down menu The New File Name dialog will be displayed 3 In the dialog browse to the folder where you want to save the file 4 In the File N
305. les Program Memory ROM Program Memory ROM is used for permanent saving program CODE being exe cuted and it is divided into two sections Boot Program section and the Application Program section The size of these sections is configured by the BOOTSZ fuse These two sections can have different level of protection since they have different sets of Lock bits Depending on the settings made in compiler program memory may also used to store a constant variables The AVR executes programs stored in program memory only coae memory type specifier is used to refer to program memory A Program Memory Data Memory Data memory consists of Rx space Memory Extended Memory MCU dependent Internal SRAM MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 105 CHAPTER 4 8051 Specifics mikroBasic PRO for AVR Rx space consists of 32 general purpose working 8 bit registers RO R31 These registers have the shortest fastest access time which allows single cycle Arith metic Logic Unit ALU operation Memory space contains addresses for CPU peripheral function such as Control registers SPI and other I O functions Due to the complexity some AVR microcontrollers with more peripherals have Extended I O memory which occupies part of the internal SRAM Extended memory is MCU dependent Storing data in and Extended memory is handled by the compiler only Users can
306. library functions for floating point math handling See also Predefined Globals and Constants for the list of predefined math constants Library Functions acos asin atan atan2 ceil COS cosh eval poly exp fabs floor frexp Idexp log log10 modf pow sin sinh sqrt tan tanh acos Prototype sub function acos dim x as real as real The function returns the arc cosine of parameter x that is the value whose Description cosine is x The input parameter x must be between 1 and 1 inclusive The return value is in radians between 0 and d inclusive asin Prototype sub function asin dim x as real as real The function returns the arc sine of parameter x that is the value whose sine is Description x The input parameter x must be between 1 and 1 inclusive The return value is in radians between 2 and 2 inclusive MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 485 CHAPTER 6 Libraries mikroBasic PRO for AVR atan Prototype sub function atan dim arg as real as real The function computes the arc tangent of parameter arg that is the value Description whose tangent is arg The return value is in radians between 2 and 2 inclusive atan2 Prototype sub function atan2 dim y as real dim x as real as real This is the two argument arc tangent function It is similar to computing the arc tangent of y
307. ll be written Valid values 0 7 color Color parameter Valid values 0 2 The parameter color determines the color of the text 0 white 1 black and 2 inverts each dot Note For x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see Glcd Init routines Use the SPI Glcd Set Font to specify the font for display if no font is speci fied then the default 5x8 font supplied with the library will be used Write text Hello world on the position 10 inside the page 2 SPI Gled Write Text Hello world 10 2 1 KA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 401 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI Glcd Image Prototype sub procedure SPI Glcd Image dim const image as byte Nothing Displays bitmap on Glcd Parameters image image to be displayed Bitmap array can be located in both code and Description RAM memory due to the mikroBasic PRO for AVR pointer to const and pointer to RAM equivalency Use the mikroBasic PRO s integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for display ing on Glcd Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Draw image my image on Glcd SPI Glcd Image my image Library Example The example demonstrates how to communicate to KS0108 Glcd via the SPI module
308. ly assigned See Cf Fat Assign dim size as longword CE Fat Reset size Cf Fat Read Prototype sub procedure Cf Fat Read dim byref bdata as byte Reads a byte from currently assigned file opened for reading Upon function execution file pointers will be set to the next character in the file Description Parameters bdata buffer to store read byte to Upon this function execution read byte is returned through this parameter CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign File must be open for reading See Cf Fat Reset dim character as byte Or Pat Read character MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 199 CHAPTER 6 Libraries mikroBasic PRO for AVR Cf Fat Rewrite Description Opens currently assigned file for writing If the file is not empty its content will be erased open file for writing Cf Fat Rewrite CF card and CF library must be initialized for file operations See Cf Fat Init Requires The file must be previously assigned See Cf Fat Assign Cf Fat Append Opens currently assigned file for appending Upon this function execution file Description pointers will be positioned after the last byte in the file so any subsequent file writing operation will start from there CF card and CF library must be initialized for file operations See Cf Fat Init File must be pre
309. m SPExpanderCS Direction as sbit sfr external Library Routines Expander Init ExpanderRST as ExpanderRST as Description Chip Select line Direction of the Reset pin Direction of the Chip Select pin Expander Read Byte Expander Write Byte Expander Read PortA Expander Read PortB Expander Read PortAB Expander Write PortA Expander Write PortB dim SPExpanderRST as sbit at PORTB BO dim SPExpanderCS as sbit at PORTB B1 dim SPExpanderRST Directi on as sbit at DDRB BO dim SPExpanderCS Directio ns sbit at DDRB B1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 289 CHAPTER 6 Libraries 290 Expa Expa Expa Expa Expa Expa Expa Expander In Prototype Description mikroBasic PRO for AVR nder Write PortAB nder Set DirectionPortA nder Set DirectionPortB nder Set DirectionPortAB nder Set PullUpsPortA nder Set PullUpsPortB nder Set PullUpsPortAB it sub procedure Expander Init dim ModuleAddress as byte Nothing Initializes Port Expander using SPI communication Port Expander module settings hardware addressing enabled automatic address pointer incrementing disabled byte mode BANK 0 register adressing slew rate enabled Parameters ModuleAddress Port Expander hardware address see schematic at the bot tom of this page Global variables SPExpandercs Chip Select line SP
310. m y bottom right as byte dim color as byte Draws a rectangle on Glcd Parameters x upper left X coordinate of the upper left rectangle corner Valid values 0 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right X coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 color COlor parameter Valid values 0 2 Description The parameter color determines the color of the rectangle border 0 white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd Init routine Draw a rectangle between dots 5 5 and 40 40 Glcd Rectangle 5 5 40 40 1 226 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Glcd Box Description Requires Glcd Circle Prototype Description Requires sub procedure Glcd Box dim x upper left as byte dim y upper left as byte dim x bottom right as byte dim y bottom right as byte dim color as byte Nothing Draws a box on Glcd Parameters x upper left X coordinate of the upper left box corner Valid values 0 127 y upper left y coordinate of the upper left box corner Valid values 0 63 x bottom right X coordinate of the lower right box corner Valid values 0 127 bottom right y coordinate of the lower right box corn
311. m ss as byte seconds dim mn as byte minutes dim hh as byte hours dim md as byte day in month from 1 to 31 dim wd as byte day in week monday 0 tuesday 1 sunday 6 dim mo as byte month number from 1 to 12 and not from O0 to 11 as with unix C time dim yy as word year Y2K compliant from 1892 to 2038 end structure MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 497 CHAPTER 6 Libraries mikroBasic PRO for AVR TRIGONOMETRY LIBRARY The mikroBasic PRO for AVR implements fundamental trigonometry functions These functions are implemented as look up tables Trigonometry functions are implemented in integer format in order to save memory Library Routines sinE3 cosE3 sinE3 Prototype sub function sinE3 dim angle deg as word as integer The function returns the sine of input parameter The function calculates sine multiplied by 1000 and rounded to the nearest integer result round sin angle deg 1000 Description Parameters angle deg input angle in degrees Note Return value range 1000 1000 dim res as integer res sinE3 45 Uo result is 707 498 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries cosE3 Prototype sub function cosE3 dim angle deg as word as integer The function returns the cosine of input parameter The function calculates cosine multiplied by 1000 and rounded
312. mentation is not allowed before else Not enough elements expected ss but s elements found Too many elements expected ss elemente external is allowed for global declarations only Destination size Ss does not match source size ss Routine prototype is different from previous declaration Division by zero Uart module cannot be initialized with selected baud rate device clock cannot be of 5 type Warning Messages Implicit typecast of integral value to pointer Library 2s was not found in search path Interrupt context saving has been turned off Variable 5 is not initialized Return value of the function s is not defined Identifier 5 overrides declaration in uni ngam Generated baud rate is bps error 5 percent Result size may exceed destination array size Infinite loop Implicit typecast performed from ss to ss Source size s does not match destination size ss Array padded with zeros Ss in order to match declared size ss Suspicious pointer conversion Hint Messages Constant ss has been declared but not used Variable 5 has been declared but not used Unit ss hes been recompiled Variable 98 been eliminated by optimizer Compiling unit ngg MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 79 CHAPTER 2 Environment mikroBasic PRO
313. meter Parameters id message identifier storage address rd data data buffer an array of bytes up to 8 bytes in length data len data length storage address CAN RX MSG FLAGS message flags storage address The CANSPI module must be in a mode in which receiving is possible See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page check the CANSPI module for received messages If any was received do something dim msg rcvd rx flags data len as byte rd data as byte 8 msg id as longint CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode CANSPI module must be in mode in which receive is possible rx flags 0 Clear message flags if msg rcvd CANSPIR ad msg id rd data data l n rx flags end if 180 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries CANSPIWrite sub function CANSPIWrite dim id as longint dim byref wr data as 8 dim data len as byte dim CAN TX MSG FLAGS as byte as byte 0 if all Transmit Buffers are busy OxFF if at least one Transmit Buffer is available Description If at least one empty Transmit Buffer is found the sub function sends message in the queue for transmission Parameters id
314. meters are always passed to procedure by value to pass argument by address add the keyword byref ahead of identifier Local declarations are optional declaration of variables and or constants local for the given procedure Procedure body is a sequence of statements to be execut ed upon calling the procedure Calling a procedure A procedure is called by its name with actual arguments placed in the same sequence as their matching formal parameters The compiler is able to coerce mis matching arguments to the proper type according to implicit conversion rules Upon procedure call all formal parameters are created as local objects initialized by val ues of actual arguments Procedure call is a self contained statement 132 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference Example Here s an example procedure which transforms its input time parameters preparing them for output on Lcd sub procedure time prep dim byref sec min hr as byte sec sec and 5 0 gt gt 4 10 sec and SOF min min and 5 0 gt gt 4 10 min and SOF hr hr and SFO gt gt 4 10 hr and SOF end sub Function Pointers Function pointers are allowed in mikroBasic PRO for AVR The example shows how to define and use a function pointer Example Example demonstrates the usage of function pointers It is shown how to declare a procedural type a poi
315. mikroBasic PRO for AVR provides routines for implementing Software Il C com munication These routines are hardware independent and can be used with any MCU The Software library enables you to use MCU as Master 1 communi cation Multi master mode is not supported Note This library implements time based activities so interrupts need to be dis abled when using Software I C Note All Software I C Library functions are blocking call functions they are waiting for I C clock line to become logical Note The pins used for Software communication should be connected to the pull up resistors Turning off the LEDs connected to these pins may also be required External dependencies of Soft I2C Library The following variables must be defined in all projects using Soft 12 Library E I26 Sel Output Soft 2 Clock output line d I2C Sel Output as sbit sfr external as sbit at PORTC BO I2C Sda Output Soft 2 Data output line I2C Sda Output as sbit sfr external as sbit at 1 2 _I2C Scl Input Soft 2 Clock input line a _I2C_Scl Input as sbit sfr external sbit at PINC BO Description E 12C Input as Soft 2C Data input line I2C Sda Input as sbit sfr external sbit at PINC B1 dim po Direction of the Soft 2 Sort Sol Pin Dire ction as sbit sfr in ction as sbit at external DDRC B0 dim dim Soft I2C Sda Pin Dire Direction of the Soft 2
316. mory address or a dereferenced value of an object for example mystring Or PORTB memcpy Prototype sub procedure memcpy dim pl 2 as byte dim nn as word The function copies nn words from the memory area starting at the address to the memory area starting at p1 If these memory buffers overlap the memcpy function cannot guarantee that words are copied before being overwritten If these buffers do overlap use the memmove function Description For parameters p1 and p2 you can use either a numerical value literal vari able constant indicating memory address or a dereferenced value of an object for example mystring Or PORTB memmove Prototype sub procedure memmove dim pl 2 as byte dim nn as word The function copies nn words from the memory area starting at the address p2 to the memory area starting at p1 If these memory buffers overlap the Memmove function ensures that the words in p2 are copied to p1 before being overwritten Description For parameters p1 and p2 you can use either a numerical value literal vari able constant indicating memory address or a dereferenced value of an object for example mystring Or PORTB 490 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries memset Prototype 4 memset dim p as byte dim character as byte dim n The function fills the first n words in the memory area starting at the
317. mp ICMP requests are replied automatically upon TCP request the Spi Ethernet UserTCP function is called for further processing upon UDP request the Spi Ethernet UserUDP function is called for further processing Description Note spi Ethernet doPacket must be called as often as possible in user s code Requires Ethernet module has to be initialized See Spi Ethernet Init TRUE i Ethernet doPacket process received packets MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Spi Ethernet putByte Prototype sub procedure Spi Ethernet putByte dim v as byte This is MAC module routine It stores one byte to address pointed by the cur rent xNc28360 write pointer EwRPT Description Parameters v value to store Ethernet module has to be initialized See Spi_Ethernet_Init dim data as byte Spi Ethernet putByte data put an byte into ENC28J60 buffer Spi Ethernet putBytes Prototype sub procedure Spi Ethernet putBytes dim ptr as byte dim n as byte This is MAC module routine It stores requested number of bytes into ENC28360 RAM starting from current ENc28760 write pointer xvn 7 location Description Parameters ptr RAM buffer containing bytes to be written into ENC28J60 RAM n number of bytes to be written Ethernet module has to be initialized See Spi Ethernet Init dim buffer as by
318. n uary is MONTHS 0 and number of days in December is MONTHS 111 The number of assigned values must not exceed the specified length Vice versa is possible when the trailing excess elements will be assigned zeroes For more information on arrays of char refer to Strings 138 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference STRINGS A string represents a sequence of characters equivalent to an array of char It is declared like this string string length The specifier string length is a number of characters a string consists of The string is stored internally as the given sequence of characters plus a final nu11 char acter zero This appended stamp does not count against string s total length A null string is stored as a single u11 character You can assign string literals or other strings to string variables The string on the right side of an assignment operator has to be shorter than another one or of equal length For example dim msgl as string 20 dim msg2 as string 19 main msgl This is some message msg2 Yet another message msgl msg2 this is ok but vice versa would be illegal Alternately you can handle strings element by element For example dim s as 5 y mik is char literal m is char literal i is char literal k is zero is undefined 5
319. n the mikroBasic PRO for AVR installation folder or probe the Code Assistant for specific letters CtrltSpace in the Code Editor Math constants In addition several commonly used math constants are predefined in mikroBasic PRO for AVR PI 3 1415926 PI HALF 1 5707963 TWO PI 6 2831853 E 2 7182619 Predefined project level defines These defines are based on a value that you have entered edited in the current proj ect and it is equal to the name of selected device for the project If ATmega16 is selected device then ATmega16 token will be defined as 1 so it can be used for conditional compilation IFDEF ATmegal ENDIF Related topics Project level defines MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 89 CHAPTER 3 Specifics mikroBasic PRO for AVR ACCESSING INDIVIDUAL BITS The mikroBasic PRO for AVR allows you to access individual bits of 8 bit variables It also supports sbit and bit data types Accessing Individual Bits Of Variables To access the individual bits simply use the direct member selector with a vari able followed by one of identifiers BO B1 B7 or 0 1 7 with 7 being the most significant bit Clear bit 0 on PORTA PORTA BO 0 Clear bit 5 on PORTB PORTB 5 0 There is no need of any special declarations This kind of selective access is an intrinsic feature of mikroBasic PRO for AVR and can be used anywhere in the code
320. n this example are made for the EasyAVR5A board and 16 RS485 Master code 332 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries program RS485 Master Example dim dim pin dat as 10 buffer for receving sending messages i j as byte cnt as longint rs485 rxtx sbit at PORTD 2 transcieve pin rs485 rxtx pin direction as sbit at DDRD 2 met transcieve direction Interrupt routine sub procedure interrupt org 0x16 RS485Master Receive dat end sub main cnt 0 PORTA 0 clear PORTA PORTB 0 clear PORTC 0 elear PORTC DDRA OxFF set PORTA as output DDRB OxFF set PORTB as output DDRC OxFF set PORTB as output Pass pointers to UART sub functions of used UART module UART Wr Ptr UART1 Write UART Rd Ptr UART1_ Read UART Ptr UART1 Data Ready VART TX Idle Ptr QUARTI TX Idle UART1 Init 9600 initialize UART1 module Delay ms 100 RS485Master Init initialize MCU as Master dat 0 OxAA dat 1 OxFO0 dat 2 0 0 dat 4 0 ensure that message received flag is 0 dat 5 0 ensure that error flag is 0 dat 6 0 RS485Master Send dat 1 160 I bit 1 enable global interrupt RXCIE bit E enable interrupt on UART receive while TRUE if dat 5 lt gt 0 then if an error detected sig
321. nal it PORTC dat 5 f by setting PORTC end if MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 333 CHAPTER 6 Libraries mikroBasic PRO for AVR if dat 4 lt gt 0 then if message received successfully cnt 0 dat 4 0 clear message received flag j 3 for i 1 to dat 3 show data on PORTB PORTB 1 1 1 dat 0 0 1 increment received dat 0 Delay ms 1 send back to slave RS485Master Send dat 1 160 end if if cnt 100000 then if 100000 poll cycles the answer Inc PORTA was not detected signal cnt 0 failure of send messag RS485Master Send dat 1 160 if PORTA 10 then if sending failed 10 times PORTA 0 RS485Master Send dat 1 50 L send message on broadcast address end if end if wend end RS485 Slave code program RS485 Slave Example dim dat as byte 20 buffer for receving sending messages i j as byte dim rs485 rxtx pin as sbit at PORTD B2 set transeleve pin rs485 rxtx pin direction as sbit at DDRD B2 Set transcleve pin direction Interrupt routine sub procedure interrupt org 0x16 RS485Slave Receive dat end sub main PORTB 0 clear PORTB PORTC 0 lear PORTC DDRB OxFF set PORTB as output DDRC OxFF set PORTB as output 334 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Y UART Wr Ptr UART Rd Ptr UART Rdy Ptr UART
322. nction sets Port Expander s PortB pull up down resistors Prototype Parameters Description ModulecAddress Port Expander hardware address see schematic at the bottom of this page Data data for choosing pull up down resistors configuration Each bit corresponds to the appropriate pin of the PortB register Set bit enables pull up for corresponding pin Port Expander must be initialized See Expander Init Set Port Expander s PORTB pull up resistors Expander Set PullUpsPortB 0 OxFF Expander Set PullUpsPortAB sub procedure Expander Set PullUpsPortAB dim ModuleAddress as byte dim PullUps as word The function sets Port Expander s PortA and PortB pull up down resistors Prototype Parameters ModuleAddress Port Expander hardware address see schematic at the bot Description tom of this page PullUps data for choosing pull up down resistors configuration PortA pull up down resistors configuration is passed Pullups s higher byte PortB pull up down resistors configuration is passed in Pullups s lower byte Each bit corresponds to the appropriate pin of the PortA PortB register Set bit enables pull up for corresponding pin Requires Port Expander must be initialized See Expander Init Example Set Port Expander s PORTA and PORTB pull up resistors Expander Set PullUpsPortAB 0 OxFFFF MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 299 CHAPTER 6 L
323. nd Play Pin as Sound output dim Sound Play Pin as sbit sfr external Output pin sbit at PORTC B3 dim dim Sound Play Pin Direct Direction of the Sound out 8ound Play Pin Direct ion as sbit sfr ion as sbit at external DDRC B3 Library Routines Sound Init Sound Play MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 357 CHAPTER 6 Libraries mikroBasic PRO for AVR Sound Init Configures the appropriate MCU pin for sound generation Global variables Sound Play Pin Sound output pin Sound Play Pin Direction Direction of the Sound output pin must be defined before using this function Sound library connections dim Sound Play Pin as sbit at PORTC B3 dim Sound Play Pin Direction as sbit at DDRC B3 End of Sound library connections Sound Init Sound Play sub procedure Sound Play dim freq in Hz as word dim duration ms as word Nothing Generates the square wave signal on the appropriate pin Description Parameters freq in Hz Signal frequency in Hertz Hz duration ms Signal duration in miliseconds ms In order to hear the sound you need a piezo speaker or other hardware on designated port Also you must call Sound Init to prepare hardware for output before using this function Play sound of IKHz duration of 100ms Sound Play 1000 100 358 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO
324. ned statement blocks which perform a certain task based on a number of input param eters When executed a function returns value while procedure does not Functions Function is declared like this sub function function name parameter list as return type local declarations function body end sub function name represents a functions name and can be any valid identifier return type is a type of return value and can be any simple type Within parenthe ses parameter list is a formal parameter list similar to variable declaration In mikroBasic PRO for AVR parameters are always passed to a function by value To pass an argument by address add the keyword ahead of identifier Local declarations are optional declarations of variables and or constants local for the given function Function body is a sequence of statements to be executed upon calling the function Calling a function A function is called by its name with actual arguments placed in the same sequence as their matching formal parameters The compiler is able to coerce mismatching arguments to the proper type according to implicit conversion rules Upon a function call all formal parameters are created as local objects initialized by values of actu al arguments Upon return from a function a temporary object is created in the place of the call and it is initialized by the value of the function result This means that func tion call as an operand in complex e
325. nformation see mikroBasic PRO for AVR Libraries 116 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference IDENTIFIERS Identifiers are arbitrary names of any length given to functions variables symbolic constants user defined data types and labels All these program elements will be referred to as objects throughout the help don t be confused with the meaning of object in object oriented programming Identifiers can contain letters from a to z and a to z the underscore character and digits from 0 to 9 First character must be a letter or an underscore i e identifi er cannot begin with a numeral Case Sensitivity mikroBasic PRO for AVR is not case sensitive 50 Sum sum and suM are equiva lent identifiers Uniqueness and Scope Although identifier names are arbitrary within the rules stated errors result if the same name is used for more than one identifier within the same scope Simply duplicate names are illegal within the same scope For more information refer to Scope and Visibility Identifier Examples Here are some valid identifiers temperature V1 Pressure no hit dat2string SUM3 _vtext and here are some invalid identifiers 7temp NO cannot begin with a numeral Shigher NO cannot contain special characters NO cannot match reserved word j23 07 04 NO cannot contain special characters dot
326. ng the new value directly MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 81 CHAPTER 2 Environment mikroBasic PRO for AVR i Edit Valu J E 0100 0000 1000 0011 0001 0010 0110 1111 Representation Dec Hex Bin Float Char Stopwatch Window The Software Simulator Stopwatch Window is available from the drop down menu View Debug Windows Stopwatch The Stopwatch Window displays a current count of cycles time since the last Soft ware Simulator action Stopwatch measures the execution time number of cycles from the moment Software Simulator has started and can be reset at any time Delta represents the number of cycles between the lines where Software Simulator action has started and ended Note The user can change the clock in the Stopwatch Window which will recalcu late values for the latest specified frequency Changing the clock in the Stopwatch Window does not affect actual project settings it only provides a simulation Cycles Time Current Count 8 9 60 us Reset To Zero 9 ME 82 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment RAM Window The Software Simulator RAM Window is available from the drop down menu View Debug Windows RAM The RAM Window displays a map of MCU s RAM with recently changed items col ored red You can change val
327. ng certain values There are two types of selection statements if select case IF STATEMENT Use the keyword if to implement a conditional statement The syntax of the if state ment has the following form if expression then statements else other statements end if When expression evaluates to true statements execute If expression is false other statements execute The expression must convert to a boolean type oth erwise the condition is ill formed The 1 keyword with an alternate block of state ments other statements is optional Nested if statements Nested if statements require additional attention A general rule is that the nested conditionals are parsed starting from the innermost conditional with each else bound to the nearest available i on its left if expressionl then if expression2 then statementl else statement2 end if end if The compiler treats the construction in this way if expressionl then if expression2 then statementl else statement2 end if end if MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 153 CHAPTER 5 Language Reference mikroBasic PRO for AVR 154 In order to force the compiler to interpret our example the other way around we have to write it explicitly if expressionl then if expression2 then statementl end if else statement2 end if SELECT CASE STATEMENT Use the select case statement to pass control to a specific program
328. ng this function set compact flash pinout dim CF Data Port as byte at PORTD dim Cf Data Port Direction as byte at DDRD dim CF R as sbit at PINB B7 dim CF WE as sbit at PORTB B6 dim CF as sbit at PORTB B5 dim CF CD1 as sbit at PINB B4 dim CF 1 as sbit at PORTB B3 dim CF as sbit at PORTB B2 dim CF Al as sbit at PORTB B1 dim CF sbit at PORTB BO dim CF RDY direction as sbit at dim CF WE direction as sbit at dim CF OE direction as sbit at dim CF cpi direction as sbit at dim CF 1 direction as sbit at dim CF A2 direction as sbit at dim CF A1 direction as sbit at dim CF _ 0 direction as sbit at end of cf pinout EJ RJ tJ d C ky Mine Cr MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Cf Detect 1 if CF card was detected 0 otherwise Checks for presence of CF card by reading the chip detect pin The corresponding MCU ports must be appropriately initialized for CF card See Cf Init sub function CF Detect as byte Wait until CF card is inserted while Cf Detect 0 nop sub procedure Cf Enable Nothing sub procedure Cf Disable Nothing The corresponding MCU ports must be appropriately initialized for CF card See Cf Init disable compact flash Disable MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 193
329. ng this routine otherwise it will have no effect as the PWM module is not ini Starts the PWM 16bit module Starts the PWM 16bit module Stops the PWM 16bit module connected to Timer Counter set in this stop function MCU must module to use this library Like in PWM16bit Start before PWM16bit Init must be called before using this routine otherwise it will have no effect as the PWM module is not running PWM16bit Stop Timer Counterl or PWM16bit_ Stop Timer Counter3 Library Example TIME TIME Stops the PWM 16bit module on Stops the PWM 16bit module on The example changes PWM duty ratio continually by pressing buttons on PORTC 0 3 If LED is connected to PORTB B1 or PORTB B2 you can observe the gradual change of emitted light This example is written for ATmega168 This AVR MCU has only Timer Counter1 split over two chan nels A and B In this example we are changing the duty ratio on both of these channels 322 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR program PWM Test dim current duty as byte current dutyl as byte main DDCO bit 0 DDCl bit 0 502 Bit e 9 Mit 8 current duty 127 current dutyl 127 1 bit 1 for the PWM according DDB2 bit 1 for the PWM according PWM16bit Init to datasheet PWM16 FAST MODE 9BIT CHAPTER 6 Libraries Set Set PORTC PORTC
330. ngle corner yl y coordinate of the lower right rectangle corner pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI 6963 Config routine Example erre 20 ree O Description 428 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI T6963C Box Prototvpe bred procedure SPI T6963C Box dim 0 as integer dim y0 as integer xl as integer dim yl as integer dim pcolor as byte Draws a box on the Glcd Parameters x0 X coordinate of the upper left box corner Description y0 y coordinate of the upper left box corner x1 X coordinate of the lower right box corner yl y coordinate of the lower right box corner pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Eee jn T6963C 0 119 239 T6963C WHITE SPI T6963C Circle sub procedure SPI T6963C Circle dim x as integer dim y as inte ger dim r as longint dim pcolor as byte Draws a circle on the Glcd Parameters Description gt x coordinate of the circle center y y coordinate of the circle center r radius size pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6
331. nika mikroBasic PRO for AVR uses Add directory to the search path list SP C Led directory to the search path list Lcd mbas Lib Math mcl Lib MathDouble mcl Lib System mcl Lib Delays mcl Lib LcdConsts mcl Lib Lcd mcl Specify input files MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 67 CHAPTER 2 Environment mikroBasic PRO for AVR PROJECTS The mikroBasic PRO for AVR organizes applications into projects consisting of a single project file extension mcpav and one or more source files extension mikroBasic PRO for AVR IDE allows you to manage multiple projects see Project Manager Source files can be compiled only if they are part of a project The project file contains the following information project name and optional description target device device flags config word device clock list of the project source files with paths image files other files Note that the project does not include files in the same way as preprocessor does see Add Remove Files from Project NEW PROJECT The easiest way to create a project is by means of the New Project Wizard drop down menu Project New Project or by clicking the New Project Icon from Project Toolbar 68 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment New Project Wizard Steps Start creating your New pro
332. nit TWI Busy TWI Start TWI Stop TWI Read TWI Write TWI Status TWI Close TWI Init Prototype sub procedure TWI Init dim clock as longword Initializes TWI with desired clock refer to device data sheet for correct values in respect with Fosc Needs to be called before using other functions of TWI Library Description You don t need to configure ports manually for using the module library will take care of the initialization Library requires MSSP module on PORTB or PORTC TWI Busy Prototype sub function TWI Busy as byte Returns Returns 0 if TWI start sequnce is finished 1 if TWI start sequnce is not finished Signalizes the status of TWI bus TWI must be configured before using this function See TWI Init if TWI Busy 1 end if MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 465 CHAPTER 6 Libraries mikroBasic PRO for AVR TWI_ Start Returns If there is no error function returns 0 otherwise returns 1 Determines if TWI bus is free and issues START signal TWI must be configured before using this function See TWI Init if TWI Start 1 end if TWI Read Prototype sub function TWI Read dim ack as byte as byte Returns Returns one byte from the slave ar Reads one byte from the slave and sends not acknowledge signal if parameter Description SAP ack is 0 otherwise it sends acknowledge TWI must be configured before using this
333. nit Prototype Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD sub procedure SPI Glcd Init dim DeviceAddress as byte Nothing Initializes the Glcd module via SPI interface Parameters DeviceAddress expander hardware address see schematic at the bottom of this page Global variables SPExpandercs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function SPI module needs to be initialized See SPI1 Init and SPI1 Init Advanced routines port expander pinout definition dim SPExpanderCS as sbit at PORTB B1 SPExpanderRST as sbit at PORTB BO SPExpanderCS Direction as sbit at DDRB B1 SPExpanderRST Direction as sbit at DDRB BO If Port Expander Library uses 5 1 module SPI1 Init Advanced SPI MASTER SPI DIV2 SPI CLE HI TRAIL ING Initialize SPI module used with PortExpander SPI Rd Ptr 85 1 Read Read function of used SPI module GLed Maat 0 Pass pointer to SPI 391 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI Glcd Set Side Prototype sub procedure SPI Glcd Set Side dim x pos as byte Selects Glcd side Refer to the Glcd datasheet for detail explanation Parameters x pos position on x axis Valid values 0 127 Description The parameter x pos
334. nitialized See SPI T6963C Config routine Example SPI T6963C Sprite 76 4 einstein 98 119 T draw sprite 430 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI T6963C Set Cursor Prototype sub procedure SPI T6963C set cursor dim x y as byte Sets cursor to row x and column y Description Parameters x cursor position row number y cursor position column number Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example ___ SPI T6963C ClearBit Prototype sub procedure SPI T6963C clearBit dim b as byte Clears control port bit s Description Parameters b bit mask The function will clear bit x on control port if bit in bit mask is set to 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine bits 0 and 1 on control port SPI T6963C ClearBit 0x03 SPI T6963C SetBit Prototype sub procedure SPI T6963C setBit dim b as byte Sets control port bit s Description Parameters b bit mask The function will set bit x on control port if bit x in bit mask is set to 1 Toshiba Glcd module needs to be initialized See SPI 6963 Config routine set bits 0 and 1 on control port SPI T6963C SetBit 0x03 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 431 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI T
335. not use this memory space for storing their data Internal SRAM Data Memory is used for temporarily storing and keeping interme diate results and variables static link and dynamic link There are four memory type specifiers that can be used to refer to the data memo ry rx data io sfr i register AVR memory RAM memory spaces space Register Space gt yo Space SRAM Data Space Related topics Accessing individual bits SFRs Memory type specifiers 106 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 4 mikroBasic PRO for AVR 8051 Specifics MEMORY TYPE SPECIFIERS The mikroBasic PRO for AVR supports usage of all memory areas Each variable may be explic assigned to a specific memory space by including a memory type specifier in the declaration or implicitly assigned The following memory type specifiers can be used code data rx 3 SET register Memory type specifiers can be included in variable declaration For example dim data buffer as byte data puts data buffer in data ram const txt Enter parameter code puts text in program memory Description The code memory type may be used for allocating constants in program memory puts txt in program memory const txt Enter parameter code This memory specifier is used when storing variable to the internal data SRAM puts data butter data ram dim data bu
336. ns 4 i Icon Description Comment selected code or put single line comment if there is no selection Uncomment selected code or remove single line comment if there is no selection Select text from starting delimiter to ending delimiter Go to ending delimiter Go to line Indent selected code lines Outdent selected code lines Generate HTML code suitable for publishing current source code on the web E Her 228 Find Replace Toolbar 1 uus Find Replace Toolbar is a standard toolbar with following options Icon Description Find text in current editor Find next occurence Find previous occurence Replace text Find text in files 20 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Project Toolbar Project Toolbar comes with following options Description Icon Fy Open new project wizard wizard Open Project skl Save Project Add existing project to project group Remove existing project from project group Add File To Project Remove File From Project pi Close current project Build Toolbar Build Toolbar comes with following options Icon Description Build current project Build
337. nstant cannot be assigned to Constant array must be declared as global Incompatible types ss to 5 Too many characters 3s Soft Uart cannot be initialized with selected baud rate device clock Main label cannot be used in modules Break Continue cannot be used out of loop Preprocessor Error ss Expression is too complicated Duplicated label ss Complex type cannot be declared here Record is empty Unknown type 25 File not found ss Constant argument cannot be passed by reference Pointer argument cannot be passed by reference 78 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Operator not applicable to these operands 3s Exit cannot be called from the main block Complex type parameter must be passed by reference Error occured while compiling 5 Recursive types are not allowed Adding strings is not allowed use strcat procedure instead Cannot declare pointer to array use pointer to structure which has array field Return value of the function 5 is not defined Assignment to for loop variable is not allowed 3s is allowed only in the main program Start address of ss has already been defined Simple constant have fixed address Invalid date time format Invalid operator 3s File 2s is not accessible Forward routine 25 is missing imple
338. nter to function and finally how to call a function via pointer program Example typedef TMyFunctionType function dim paraml param2 as byte dim param3 as word as word First define the procedural type dim MyPtr as TMyFunctionType This is a pointer to previously defined type dim sample as word sub function Funcl dim pl p2 as byte dim p3 as word as word Now define few functions which will be pointed to Make sure that param eters match the type definition result pl and p2 or p3 end sub sub function Func2 dim abc def as byte dim ghi as word as word Another function of the same kind Make sure that parameters match the type definition result abc def ghi end sub sub function Func3 dim first yellow as byte dim monday as word as word Yet another function Make sure that parameters match the type definition result monday yellow first end sub MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 133 CHAPTER 5 Language Reference mikroBasic PRO for AVR main program main MyPtr Funcl MyPtr now points to Funcl Sample MyPtr 1 2 3 Perform function call via pointer call Funcl the return value is 3 MyPtr Func2 MyPtr now points to Func2 Sample MyPtr 1 2 3 Perform function call via pointer call Func2 the return value is 5 MyPtr Func3 MyPtr now points to Func3 Sample MyPtr 1 2 3 Perform function call via pointer call Func
339. o Try to synchronize again Man Receive Init Alternative try to Initialize Receiver again ErrorCount 0 Reset error counter end if else No error occured if temp lt gt 0 0 then If End byte was received see Transmitter example Lcd Chr CP temp do not write received byte on Lcd end if Delay ms 25 end if wend If End byte was received exit do loop wend end The following code is code for the Manchester transmitter it shows how to use the Manchester Library for transmitting data program Manchester Transmitter Manchester module connections dim MANRXPIN as sbit at PORTB BO MANRXPIN Direction as sbit at DDRB BO as sbit at PORTB B1 MANTXPIN Direction as sbit at DDRB B1 End Manchester module connections dim index character as byte sl as char 17 main gi mikroElektronika Man Send Init while TRUE Man 0 0 Delay ms 100 character 51 0 i index 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Initialize transmitter Endless loop Send start byte Wait for a while Take first char from string Initialize index variable 253 CHAPTER 6 Libraries mikroBasic PRO for AVR while character lt gt 0 String ends with zero Man Send character Send character Delay ms 90 Wait for a while Inc index Increment index variable character s1 index Take next char from string wend
340. o i 1 1 IE i i 1 gt osc2 i i n RxiB SL 1 gt i m i TX CAN RS 1 24 cann i O 3 Avec cant 4 Shielded L twisted pair E Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface 188 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries COMPACT FLASH LIBRARY The Compact Flash Library provides routines for accessing data on Compact Flash card abbr CF further in text CF cards are widely used memory elements com monly used with digital cameras Great capacity and excellent access time of only a few microseconds make them very attractive for the microcontroller applications In CF card data is divided into sectors One sector usually comprises 512 bytes Routines for file handling the Cf Fat routines are not performed directly but suc cessively through 512B buffer Note Routines for file handling can be used only with FAT16 file system Note Library functions create and read files from the root directory only Note Library functions populate both FAT1 and FAT2 tables when writing to files but the file data is being read from the FAT1 table only i e there is no recovery if the FAT1 table gets corrupted Note If MMC SD card has Master Boot Record MBR the library will work with the first available primary logical partition that
341. o be initialized See SPI T6963C Config routine clear current graphic panel SPI T6963C GrFill 0 SPI T6963C TxtFill Prototype sub procedure SPI T6963C TxtFill dim v as byte Fill current text panel with appropriate value 0 to clear Description Parameters v this value increased by 32 will be used to fill text panel Toshiba Glcd module needs to be initialized See SPI T6963C Config routine clear current text panel SPI T6963C TxUFELII Q 434 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI T6963C Cursor Height Prototype sub procedure SPI T6963C Cursor Height dim n as byte Set cursor size Description Parameters n cursor height Valid values 0 7 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C Graphics Prototype sub procedure SPI T6963C Graphics dim n as byte Enable disable graphic displaying Parameters Description n graphic enable disable parameter Valid values 0 disable graphic dispaying and 1 enable graphic displaying Toshiba Glcd module needs to be initialized See SPI T6963C Config routine enable graphic displaying SPI T6963C Graphics 1 SPI T6963C Text Prototype sub procedure SPI T6963C Text dim n as byte Enable disable text displaying er Parameters Description n text enable disable parameter Val
342. oBasic PRO for AVR Mmc Fat Reset Prototype sub procedure Mmc Fat Reset dim byref size as longword Opens currently assigned file for reading Description Parameters size buffer to store file size to After file has been open for reading its size is returned through this parameter MMC SD card and MMC library must be initialized for file operations See Fat Init The file must be previously assigned See Mmc Fat Assign dim size as longword main Mmc Fat Reset size end 264 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc Fat Read Prototype sub procedure Mmc Fat Read dim byref bdata as byte Nothing Reads a byte from the currently assigned file opened for reading Upon function execution file pointers will be set to the next character in the file Description Parameters bdata buffer to store read byte to Upon this function execution read byte is returned through this parameter MMC SD card and MMC library must be initialized for file operations See Fat Init The file must be previously assigned See Mmc Fat Assign The file must be opened for reading See Mmc Fat Reset dim character as byte main Mmc Fat Read character end Mmc Fat Rewrite Description Opens the currently assigned file for writing If the file is not empty its content will be erased MMC SD card and MMC library must be ini
343. oStr weeks hile eee odd eee Ohba RE Eb din cbe 479 Word TOSlE i a rE EEEE ERENER de Wala x ae eee hs als ate 479 IntIOStE 3 csc ecieyeni vb es as 480 Lonan 480 LongWordToStr 2 2 1 481 FloatTOStt 24 edere ee a 482 0 2 MET 483 2 16 2 be a oe d 483 Dec2Bcd10 cores e ev esed Rer ars 484 Math Library siis e cast ydp D d PERRA Prud bare 485 Library F nclions xe uae EGRE A Ede 485 XXIV MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Table of Contents ACOS 485 PPP 485 aa a S 486 486 DAS eee e d eG 486 COS TE 486 Mori MR 486 VAL EET T 486 EXD 487 IL 487 es soa qe 487 o UP 487 EXD PITT 487 c M 487 iei TT 487 MOOR ocu thse ee ee ee UI Su si M MES 488 DOW ede deer ee Be i Vat eoa a ar So re V bn ae 488 488 DU SS 488 SQit dE Es 488 x 488 OE ee se 488 String LIBRARY sister t eae E t na EE 489
344. oes 12 Main Menu Options 13 File Menu Options 14 Edit Menu Options 15 Find Text eec ied Lb edie 16 Dialog DOX 16 sos ey m e MAU piu 17 GO TO LING Ts ee oc ates o o Wheat RS 17 Regular expressions 17 View Menu Options 18 Toolbars 2s cis eae newer REDE ew ea RE Ee YN ve 19 File Toolbat eem ec pea d 19 am UOS ee c RC RU e X RR Ud 19 Advanced Edit 20 Find Replace 20 Project 1 21 Build Toolbar x RUE CR ROS 21 IV MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Table of Contents ea Raa 22 olyles Toolbar RR d ER 22 Tools Toolbar el ok ed bec 23 Project Menu Options 24 Run Menu Options 26 Tools Menu Options
345. oft UART Read Prototype Description sub function Soft UART Read dim byref error as byte as byte Byte received via UART The function receives a byte via software UART This is a blocking function call waits for start bit Programmer can unblock it by calling Soft Break routine Parameters error Error flag Error code is returned through this variable 0 no error 1 Stop bit error 255 user abort Soft UART Break called Software UART must be initialized before using this function See the Soft UART Init routine dim data as byte error as byte wait until data is received do data Soft Uart Read error loop until error 0 Now we can work with data if data then end if MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 353 CHAPTER 6 Libraries mikroBasic PRO for AVR Soft UART Write 354 Prototype sub procedure Soft UART Write udata as byte This routine sends one byte via the Software UART bus Description Parameters udata data to be sent Software UART must be initialized before using this function See the Soft UART Init routine Be aware that during transmission software UART is incapable of receiving data data transfer protocol must be set in such a way to prevent loss of infor mation dim some byte as byte Write a byte via Soft Uart some byte 0x0A Soft Uart Write some byte MIKROELEKTRONIKA SOFTWARE AND HARD
346. ommands Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routines Clear Lcd display SPI Lcd8 Cmd LCD CLEAR Available Lcd8 Commands Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected LCD RETURN HOME Shift display left without changing display data RAM Shift display right without changing display data RAM MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 417 CHAPTER 6 Libraries mikroBasic PRO for AVR Library Example This example demonstrates how to communicate Lcd in 8 bit mode via the SPI mod ule using serial to parallel convertor 23517 program Spi Lcd8 Test dim text as char 16 Port Expander module connections dim SPExpanderRST as sbit at PORTB 0 SPExpanderCS as sbit at PORTB 1 SPExpanderRST Direction as sbit at 0 SPExpanderCS Direction sbit at DDRB 1 End Port Expander module connections main text mikroE If Port Expander Library uses SPI1 module SPIL Init Initialize SPI mod ule used with PortExpander Spi Rd Ptr 8SPII Read Pass pointer to SPI Read sub function of used SPI module If Port Expander Library uses SPI2 module SPI2 Init Initialize SPI mod ule used with PortExpander Spi Rd Ptr amp SPI2 Read Pass pointer to SPI Read sub function of used SPI module
347. on 9 Forward Whole words only Search from caret Backward 16 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Find In Files Dialog box for searching for a text string in current file all opened files or in files on a disk The string to search for is specified in the Text to find field If Search in directories option is selected The files to search are specified in the Files mask and Path fields Text to find Options Where Case sensitive Current file lo fil Go To Line Dialog box that allows the user to specify the line number at which the cursor should be positioned Regular expressions By checking this box you will be able to advance your search through Regular expressions Search for unsigned x20int E Related topics Keyboard shortcuts Edit Toolbar Advanced Edit Toolbar MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 17 CHAPTER 2 Environment mikroBasic PRO for AVR VIEW MENU OPTIONS Toolbars Debug Windows Routines List Project Settings Code Explorer Project Manager Ctrl F 11 Library Manager Bookmarks v Messages Macro Editor Windows File Description Debug Windows Show Hide debug windows T Routines List Show Hide Routine List in active editor Project Settin
348. opriate pin of the PortA register Set bit designates corresponding pin as input Cleared bit designates corresponding pin as output Requires Port Expander must be initialized See Expander Init Set Port Expander s PORTA to be output Expander Set DirectionPortA 0 0x00 Expander Set DirectionPortB sub procedure Expander Set DirectionPortB dim ModuleAddress as byte dim Data as byte Nothing The function sets Port Expander s PortB direction Prototype Parameters Description 4oduieaddress Port Expander hardware address see schematic at the bottom of this page Data data to be written to the PortB direction register Each bit corresponds to the appropriate pin of the PortB register Set bit designates corresponding pin as input Cleared bit designates corresponding pin as output Requires Port Expander must be initialized See Expander Init Example Set Port Expander s PORTB to be input Expander Set DirectionPortB 0 0xFF MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 297 CHAPTER 6 Libraries mikroBasic PRO for AVR Expander Set DirectionPortAB sub procedure Expander Set DirectionPortAB dim ModuleAddress as byte dim Direction as word Nothing The function sets Port Expander s PortA and PortB direction Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Direction data to be written to direction r
349. or AVR HW Connection o 89LVOANLV PWM demonstration 324 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries RS 485 LIBRARY RS 485 is a multipoint communication which allows multiple devices to be connect ed to a single bus The mikroBasic PRO for AVR provides a set of library routines for comfortable work with RS485 system using Master Slave architecture Master and Slave devices interchange packets of information Each of these packets con tains synchronization bytes CRC byte address byte and the data Each Slave has unique address and receives only packets addressed to it The Slave can never ini tiate communication It is the user s responsibility to ensure that only one device transmits via 485 bus at a time The RS 485 routines require the UART module Pins of UART need to be attached to RS 485 interface transceiver such as LTC485 or similar see schematic at the bottom of this page Library constants START byte value 150 STOP byte value 169 Address 50 is the broadcast address for all Slaves packets containing address 50 will be received by all Slaves except the Slaves with addresses 150 and 169 Note Prior to calling any of this library routines UART Wr Ptr needs to be initialized with the appropriate UART Write routine Prior to calling any of this library routines UART Rd Ptr needs to be initial
350. ormulas are shown below PHASE f EK vo MODE N 510 255 1 Duty Ratio Y 2tewm 3towm Atrum Stew 6tewn 7 town Non Inverted Description Inverted _ fax i o N 256 255 t Duty Ratio K 7 Non Inverted Inverted t PWM Init must be called before using other functions from PWM Library 310 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries You need a CMO on the given MCU that supports PWM Before calling this routine you must set the output pin for the PWM according to the datasheet DDRB 3 1 set PORTB pin 3 as output for the This code oxample is for ATmega16 for different MCU please consult datasheet for the correct pinout of the PWM module or modules Initialize PWM module PWM Init PWM FAST MODE ER 8 PWM NON INVE 127 PWM Set Duty Prototype sub procedure PWM Set Duty dim duty as byte Changes PWM duty ratio Parameter duty takes values from 0 to 255 where 0 Description is 0 127 is 50 and 255 is 100 duty ratio Other specific values for duty ratio can be calculated as Percent 255 100 PWM module must to be initialised PWM Init before using PWM Set Duty Requires function For example lets set duty ratio to 75 PWM Set Duty 192 PWM Start
351. oshiba module needs to be initialized See the T6963C Init routine set cursor on T6963C Cursozr l T6963C Cursor Blink Prototype sub procedure 6963 Cursor Blink dim n as byte Enable disable cursor blinking Description Parameters n on off parameter Valid values 0 disable cursor blinking and 1 enable cursor blinking Toshiba Glcd module needs to be initialized See the 6963 Init routine enable cursor blinking T6963C Cursor Blink 1 Library Example The following drawing demo tests advanced routines of the T6963C library Hardware con figurations in this example are made for the T6963C 240x128 display EasyAVR5A board and ATmega16 458 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries program T6963C 240x128 include Lib T6963C Consts include bitmap include bitmap2 T6963C module connections dim T6963C ctrlPort as byte at PORTC CONTROL port dim 6963 dataPort as byte at PORTD DATA port dim T6963C ctrlPort Direction as byte at DDRC CONTROL direc tion register dim 6963 dataPort Direction as byte at DDRD r DATA direc tion register dim T6963C ctrlwr as sbit at PORTC B2 WR write signal dim T6963C ctrlrd as sbit at PORTC BI RD read signal dim 6963 ctrlcd as sbit at PORTC BO CD command data signal dim 6963 ctrlrst as sbit at PORTC B4 RST reset signal dim T69
352. ototype sub procedure Delay ms const time in ms as longword Creates a software delay in duration of time ms milliseconds a constant Range of applicable constants depends on the oscillator frequency Description This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Requires Nothing Example Delay_ms 1000 One second pause Vdelay ms Prototype sub procedure Vdelay ms time in ms as word Creates a software delay in duration of time ms milliseconds a variable Generated delay is not as precise as the delay created by Delay ms Description Note that Vdelay ms is library function rather than a built in routine it is pre sented in this topic for the sake of convenience paupe 1000 ms pause one second pause MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroBasic PRO for AVR Specifics Delay Cyc Prototype sub procedure Delay Cyc Cycles div by 10 as byte Creates a delay based on MCU clock Delay lasts for 10 times the input param eter in MCU cycles DOSerpuon Note that Delay Cyc is library function rather than a built in routine it is pre sented in this topic for the sake of convenience There are limitations for Cycles div by 10 value Value Cycles div by 10 must be between 2 and 257 Requires Nothing Example Delay Cyc 10 Hundred MCU cycles pause
353. otype sub function floor dim x as real as real The function returns the value of parameter x rounded down to the nearest integer frexp sub function frexp dim value as real dim byref eptr as integer Prototype 249 00 Y p ger The function splits a floating point value value into a normalized fraction and an Description integral power of 2 The return value is a normalized fraction and the integer exponent is stored in the object pointed to by eptr Idexp Prototype Prototype sub function ldexp dim value as real dim newexp as integer as real The function returns the result of multiplying the floating point number value by Description 2 raised to the power newexp i e returns value 2 log dissi sub function log dim x as real as real The function returns the natural logarithm of x i e Log x log10 Ep sub function logl0 dim x as real as real The function returns the base 10 logarithm of x i e 10910 x MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 487 CHAPTER 6 Libraries mikroBasic PRO for AVR modf Prototype sub function modf dim val as real dim byref iptr as real as real The function returns the signed fractional component of vai placing its whole Description number component into the variable pointed to by pow Prototype sub function pow dim x as real dim y as real as real The function returns the value of x
354. otype sub function EEPROM Read dim address as word as byte Byte from the specified address Reads data from specified address Description Parameters address address of the EEPROM memory location to be read dim eeAddr as word temp as byte eeAddr 2 temp EEPROM Read eeAddr MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 211 CHAPTER 6 Libraries mikroBasic PRO for AVR EEPROM Write Prototype sub procedure EEPROM Write dim address as word dim wrdata as byte Nothing Writes wrdata to specified address Parameters Daseriprion address address of the EEPROM memory location to be written wrdata data to be written Note Specified memory location will be erased before writing starts dim eeWrite as byte wrAddr as word eeWrite 0x02 wrAddr OxAA EEPROM Write wrAddr eeWrite 212 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example This example demonstrates using the EEPROM Library with ATmega16 MCU First some data is written to EEPROM in byte and block mode then the data is read from the same locations and displayed on PORTA PORTB and PORTC program EEPROM dim counter as byte loop variable main DDRA OxFF DDRB OxFF DDRC OxFF for counter 0 to 31 Fill data buffer EEPROM Write 0x100 4 counter counter Write data to
355. ounter 1 one more request don if getRequest 5 s then if request path name starts with s store dynamic data in transmit buffer the text string replied by this request can be interpreted as javascript statements by browsers len putConstString httpHeader HTTP header len len putConstString 8httpMimeTypeScript with text MIME type add PORTC value buttons to reply len len putString var PINC WordToStr PINC dyna len len putString dyna len len putString add PORTD value LEDs to reply len len putstring var PORTD WordToStr PORTD dyna len len_ putString dyna len len putString add HTTP requests counter to reply WordToStr httpCounter dyna Len len putString var REQ w len putstring idyna len e len putstraing s else if getRequest 5 t then if request path name starts with t toggle PORTD LED bit number that comes after bitMask 0 if isdigit getRequest 6 lt gt 0 then t if 0 lt bit number lt 9 bits 8 amp 9 does not exist but does not matter bitMask getRequest 6 0 convert ASCII to integer bitMask 1 lt lt bitMask create bit mask PORTD PORTD xor bitMask toggle PORTD with xor operator end if end if end if 386 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries if len 0 t
356. pares pairs of bits and generates a 1 result if either or both bits are 1 otherwise it returns 0 bitwise exclusive OR XOR compares pairs of bits and generates a 1 result if the bits are complementary otherwise it returns 0 bitwise complement unary inverts each bit bitwise shift left moves the bits to the left it discards the far left bit and assigns 0 to the right most bit xor bitwise shift right moves the bits to the right discards the far right bit and if unsigned assigns 0 to the left most bit otherwise sign extends The bitwise operators and or and xor perform logical operations on the priate pairs of bits of their operands The operator not complements each bit of its operand For example 148 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference 1234 and 5678 equals 1230 because 1234 0001 0010 0011 0100 5678 0101 0110 0111 1000 0001 0010 0011 0000 dehet 28 2512030 Similarly 1234 or 5678 equals 567C 1234 xor 5678 equals 444C not 51234 equals EDCB Unsigned and Conversions If number is converted from less complex to more complex data type the upper bytes are filled with zeroes If number is converted from more complex to less com plex data type the data is simply truncated upper bytes are lost For example dim a as byte dim b as word a b SFOF b
357. percent sign prefix indicates a binary numeral for example 50101 Here are some examples IL decimal literal STI hex literal equals decimal 17 0 11 hex literal equals decimal 17 11 binary literal equals decimal 3 The allowed range of values is imposed by the largest data type in mikroBasic PRO for AVR longword The compiler will report an error if the literal exceeds 4294967295 SFFFFFFFF Floating Point Literals A floating point value consists of Decimal integer Decimal point Decimal fraction e or E and a signed integer exponent optional You can omit either decimal integer or decimal fraction but not both Negative floating constants are taken as positive constants with the unary operator minus prefixed 114 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference mikroBasic PRO limits floating point constants to the range of 1 17549435082 10 38 6 80564774407 1038 Here are some examples Os v e 0 0 2 23 45e6 Ye 23 45 41076 2 5 3E 10 vom SQ 4 TOTO 09E34 0 09 10 34 Character Literals Character literal is one character from the extended ASCII character set enclosed with quotes for example 2 Character literal can be assigned to variables of byte and char type variable of byte will be assigned the ASCII value of the char acter Also you can assign c
358. pics Keyboard shortcuts Integrated Tools Debugger Windows MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 23 CHAPTER 2 Environment mikroBasic PRO for AVR PROJECT MENU OPTIONS Build Ctrl F9 Build All Projects Shift F9 4 Build Program Edit Search Paths Clean Project Folder AY Add File To Project Remove File From Project i4 New Project Shift Ctrl N 1 Open Project Shift Ctrl O Open Project Group Close Project Group 1 Save Project As Recent Projects 313 Close Project 24 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Project Description Build Ctrl F9 Build active project d Build All Shift F9 Build all projects Build Program Ctr F11 Build and program active project 24 view Assembly View Assembly Edit Search Paths Edit search paths Clean Project Folder Clean Project Folder a Add File To Project Add file to project emove File From Project Remove file from project ew Project Open New Project Wizard T4 enProject Shift Ctr O existing project IS Es Ge ave Project Save current project Open Project Group Open project group ose Project Group Close project group 08 5
359. pin must be defined before using this function OneWire pinout dim OW Bit Read as sbit at PINB B2 dim OW Bit Write as sbit at PORTB B2 dim OW Bit Direction as sbit at DDRB B2 end of OneWire pinout Read byte from the One Wire Bus dim read data as byte read data Ow Read MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 283 CHAPTER 6 Libraries Ow Write mikroBasic PRO for AVR Prototype sub procedure Ow Write dim par as byte Description Writes one byte of data via the OneWire bus Parameters par data to be written Devices compliant with the Dallas OneWire protocol Global variables OW Bit Read OneWire read line OW Bit Write OneWire write line OW Bit Direction Direction of the OneWire pin must be defined before using this function OneWire pinout dim OW Bit Read as sbit at PINB B2 dim OW Bit Write as sbit at PORTB B2 dim OW Bit Direction as sbit at DDRB B2 end of OneWire pinout Send a byte to the One Wire Bus Ow Write 0xCC 284 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example This example reads the temperature using DS18x20 connected to pin PORTB 2 After reset MCU obtains temperature from the sensor and prints it on the Lcd Make sure to pull up PORTB 2 line and to turn off the PORTB leds program OneWire Lcd module connections dim LCD RS as sbit
360. pmode 2 end select Nested Case Statements Note that the select case statements can be nested values are then assigned to the innermost enclosing select case statement ITERATION STATEMENTS Iteration statements let you loop a set of statements There are three forms of iter ation statements in mikroBasic PRO for AVR for while repeat You can use the statements break and continue to control the flow of a loop state ment break terminates the statement in which it occurs while cont inue begins exe cuting the next iteration of the sequence MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 155 CHAPTER 5 Language Reference mikroBasic PRO for AVR FOR STATEMENT The for statement implements an iterative loop and requires you to specify the num ber of iterations The syntax of the for statement is for counter initial value to final value step step value Statements next counter counter is a variable being increased by step value with each iteration of the loop The parameter step value is an optional integral value and defaults to 1 if omit ted Before the first iteration counter is set to initial value and will be incre mented until it reaches or exceeds the final value With each iteration state ments will be executed initial value and final value should be expressions compatible with counter statements be any statements that do not change the value of counter Note
361. pported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page set the appropriate filter mask and message type valu CANSPISetOperationMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPI module must be in config mode for mask settings Set all B1 mask bits to 1 all filtered bits are relevant Note that 1 is just a cheaper to write OxFFFFFFFF Complement will do the trick and fill it up with ones CANSPISetMask CANSPI MASK Bl 1 CANSPI CONFIG MATCH MSG TYPE and CANSPI CONFIG XTD MSG 178 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR CHAPTER 6 Libraries CANSPISetFilter Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD sub procedure CANSPISetFilter dim CAN FILTER as byte dim val as longint dim CAN CONFIG FLAGS as byte Nothing Configures message filter The parameter value is bit adjusted to the appropri ate filter registers Parameters CAN FILTER CANSPI module filter number Valid values CANSPI FILTE constants see CANSPI constants val filter register value CONFIG FLAGS Selects type of message to filter Valid values CANSPI CONFIG ALL VALID MSG CANSPI CONFIG MATCH MSG TYPE and CANSPI CONFIG STD MSG and CANSPI CONFIG XTD MSG
362. priate internal point ers All subsequent text operations will be preformed at this text panel Deseripuen Parameters n text panel number Valid values o and Toshiba Glcd module needs to be initialized See the T6963C Init routine set text panel 1 as current text panel T6963C SetTsxtPanel l MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 455 CHAPTER 6 Libraries mikroBasic PRO for AVR T6963C PanelFill Prototype sub procedure T6963C PanelFill dim v as byte Fill current panel in full graphic text with appropriate value 0 to clear Description Parameters v Value to fill panel with Toshiba Glcd module needs to be initialized See the T6963C Init routine clear current panel T6963C 1 111 0 T6963C GrFill Prototype sub procedure T6963C PanelFill dim v as byte Fill current panel in full graphic text with appropriate value 0 to clear Description Parameters v Value to fill panel with Toshiba Glcd module needs to be initialized See the T6963C Init routine clear current panel 5363 PanelErIl 0 T6963C TxtFill Prototype sub procedure 6963 TxtFill dim v as byte Fill current text panel with appropriate value 0 to clear Description Parameters v this value increased by 32 will be used to fill text panel Toshiba Glcd module needs to be initialized See the T6963C Init routine clear current text panel T6963C
363. put a RAM string into ENC28J60 buffer 376 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Spi Ethernet putConstString Prototype sub function Spi Ethernet putConstString const ptr as byte as word Returns Number of bytes written into ENC28J60 RAM This is MAC module routine It stores whole const string excluding null termina tion into z c28760 RAM starting from current 28 2760 write pointer EWRPT location Description Parameters ptr const string to be written into ENC28J60 RAM Ethernet module has to be initialized See Spi Ethernet Init const buffer as string 16 buffer mikroElektronika Spi Ethernet putConstString buffer put a const string into ENC28J60 buffer Spi Ethernet getByte Returns Byte read from ENC28J60 RAM This is MAC module routine It fetches a byte from address pointed to by cur rent ENC28J60 read pointer ERDPT Description Ethernet module has to be initialized See Spi Ethernet Init dim buffer as byte lt gt buffer Spi Ethernet getByte read a byte from ENC28J60 buffer MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 377 CHAPTER 6 Libraries mikroBasic PRO for AVR Spi Ethernet getBytes sub procedure Spi Ethernet getBytes dim ptr as byte dim addr as word dim n as byte Nothing This is MAC module routin
364. r word short integer short 5 longrnt integer longint integral Higher bytes of extended unsigned operand are filled with zeroes Higher bytes of extended signed operand are filled with bit sign if number is negative fill higher bytes with one otherwise with zeroes For example dim a as byte dim b as word a SFF b a is promoted to word b becomes 00FF MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 143 CHAPTER 5 Language Reference mikroBasic PRO for AVR Clipping In assignments and statements that require an expression of particular type desti nation will store the correct value only if it can properly represent the result of expression i e if the result fits in destination range If expression evaluates to more complex type than expected excess data will be simply clipped the higher bytes are lost dim i as byte dim j as word j i j i becomes SOF higher byte FF is lost EXPLICIT CONVERSION Explicit conversion can be executed at any point by inserting type keyword byte word short integer longint float ahead of the expression to be con verted The expression must be enclosed in parentheses Explicit conversion can be performed only on the operand left of the assignment operator Special case is the conversion between signed and unsigned types Explicit conver sion between signed and unsigned data does not change binary representation of
365. r as byte data 0 0 data Man Receive amp error if error lt gt 0 then error handling end if Man Send Init The function configures Transmitter pin Global variables MANRXPIN Receive line Requires MANRXPIN Direction Direction of the receive pin must be defined before using this function Initialize Transmitter dim MANTXPIN as sbit at PINB B1 dim MANTXPIN Direction as sbit at DDRB B1 Man Send Init MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 249 CHAPTER 6 Libraries mikroBasic PRO for AVR Man Send Prototype sub procedure Man Send tr data as byte Sends one byte Parameters Description tr data data to be sent Note Baud rate used is 500 bps To use this function the user must prepare the MCU for sending See Requires Man Send Init dim msg as byte Man Send msg Man Synchro Prototype sub function Man Synchro as word 0 if synchronization was not successful Half of the manchester bit length given in multiples of 10us upon successful synchronization Measures half of the manchester bit length with 10us resolution To use this function you must first prepare the MCU for receiving See Requires Man Receive Init dim man half bit len as word man half bit len Man Synchro 250 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR
366. r which compilation will be done FO Set oscillator in MHz SP Add directory to the search path list 1P Add directory to the include search list N Output files generated to file path specified by filename B Save compiled binary files mc1 to directory 0 Miscellaneous output options pBG Generate debug info L Check and rebuild new libraries DL Build all files as libraries y Dynamic link for string literals C Turn on case sensitivity Example mBAvr exe MSF DBG pATMEGAI6 G 011111114 fo8 N C Led Lcd mcpav SP C Program Files Mikroelektronika mikroBasic PRO for AVR Defs SP C Program Files Mikroelektronika mikroBasic PRO for AVR Uses LTE64KW 5 Lcd mbas Lib Math mcl Lib MathDouble mcl Bib Systemmol C Lib Delaysmor Lib LodConsts mcl Lib Lcd mcl Parameters used in the example MSF Short Message Format used for internal purposes by IDE DBG Generate debug info pATMEGA16 MCU 16 selected C Turn on case sensitivity 011111114 Miscellaneous output options 08 Set oscillator frequency in MHz N C Led Led mcpav SP C Program FilesMMikroelektronikaNmikroBasic PRO for AVR defs Output files generated to file path specified by filename SP C Program Files Mikroelektronika mikroBasic PRO for AVR defs Add directory to the search path list SP C Program Files Mikroelektro
367. rCs Chip Select line SPExpanderRST Reset line Directrons Dire SPExpanderRST SPExpanderCS Direction Dir CHAPTER 6 Libraries ction of the Chip Select pin ection of the Reset pin must be defined before using this function SPI module needs to be initialized See SPI1 Init and SPI1 Init Advanced routines port expander pinout definition dim SPExpanderCS as sbit at SPExpanderRST SPExpanderCs SPExpanderRST Direction Direction Initialize SPI module SPIL Init Advanced SPI MASTI SPI CLK HI TRAILING SPI Rd Ptr 85 1 Read PORTS B1 as sbit at PORTB BO as sbit at DDRB B1 as sbit at DDRB BO ER _SPI_FCY DIV32 Pass pointer to SPI Read function of used SPI module SPI T6963C Config 240 64 8 SPI_T6963C_WriteData 0 Prototype sub procedure SPI T6963C WriteData dim Ddata as byte Writes data to T6963C controller v Description Parameters Ddata data to be written ia SPI interface Toshiba Glcd module needs to be initialized See SPI T6963C Config routine MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 423 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI T6963C WriteCommand Prototype sub procedure SPI T6963C WriteCommand dim Ddata as byte Writes command to T6963C controller via SPI interface Description Parameters Ddata command to be written Toshiba Glcd module needs to
368. raised to the power y i e 7 If x is nega D H 1 tive the function will automatically cast into longint dinis sub function sin dim arg as real as real The function returns the sine of arg in radians The return value is from 1 to 1 sinh Prototype sub function sinh dim x as real as real The function returns the hyperbolic sine of defined mathematically as e e 2 D ipti i eseriptton if the value of is too large if overflow occurs the function fails sqrt oe sub function sqrt dim x as real as real The function returns the non negative square root of x tan Prototype Prototype sub function tan dim x as real as real function tan dim x as real as real Daseripti n ein TEE function returns the tangent of x in radians The return value spans the allowed range of floating point in mikroBasic PRO for AVR tanh Prototype Prototype sub function tanh dim x as real as real The function returns the hyperbolic tangent of x defined mathematically as sinh x cosh x Description 488 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries STRING LIBRARY The mikroBasic PRO for AVR includes a library which automatizes string related tasks Library Functions memchr memcmp memmove memset strcat strchr strcmp strcpy strlen strncat
369. raries UARTx Init Advanced Prototvpe sub procedure UARTx Init Advanced dim baud rate as longword dim parity as byte dim stop bits as byte Configures and initializes UART module Parameter baud_rate configures UART module to work on a requested baud rate Parameters parity and stop bits determine the work mode for UART and can have the following values Descrip Predefined brary const Note Some MCUs do not support advanced configuration of the UART module Please consult appropriate daatsheet MCU must have UART module Initialize hardware UART1 module and establish communication at 9600 bps 8 bit data even parity and 2 STOP bits UART1 Init Advanced 9600 UART EVENPARITY _UART TWO STOPBITS MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 471 CHAPTER 6 Libraries mikroBasic PRO for AVR UARTx Data Ready Returns Function returns 1 if data is ready or if there is no data The function tests if data in receive buffer is ready for reading MCU with the UART module The UART module must be initialized before using this routine See the Init routine dim receive as byte read data if ready if UART1 Data Ready 1 then receive VARTI Read UARTx Read Prototype sub function UARTx Read as byte Returns Received byte The function receives a byte via UART Use the UARTx_Data_Ready function to
370. rection as sbit at DDRD BO Soft UART Tx Pin Direction as sbit DDRD BI End Soft UART connections dim error counter byte read as byte Auxiliary variables main DDRB OxFF Set PORTB as output error signalization PORTB 0 No error error Soft VART Init 9600 0 Initialize Soft at 9600 bps if error gt 0 then PORTB error _ while TRUE nop wend end if Delay 100 Signalize Init error Stop program for counter z to A step 1 Send bytes from z downto Soft UART Write counter Delay ms 100 next counter while TRUE Endless loop byte read Soft UART Read error Read byte then test error flag if error lt gt 0 then If error was detected PORTB error r Signal it on else Soft UART Write byte read ed return byte read end if wend end If error was not detect 356 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SOUND LIBRARY The mikroBasic PRO for AVR provides a Sound Library to supply users with routines necessary for sound signalization in their applications Sound generation needs additional hardware such as piezo speaker example of piezo speaker interface is given on the schematic at the bottom of this page External dependencies of Sound Library The following variables must be defined in all projects using Sound Library Description dim Sou
371. rection of transition determines whether the bit is 0 or 1 the second half is the true bit value and the first half is the complement of the true bit value as shown in the figure below Manchester RF Send Byte format st1 st2 ctr B7 B6 B5 B4 3 B2 B1 B0 Bi phase coding 1 0 2 Example of transmission 11000100011 Notes The Manchester receive routines are blocking calls Man Receive Init and Man Synchro This means that MCU will wait until the task has been performed e g byte is received synchronization achieved etc Note Manchester code library implements time based activities so interrupts need to be disabled when using it External dependencies of Manchester Code Library The following variables must be defined in all projects using Man chester Code Library dim MANRXPIN as sbit 1 PIN as sbit Receive line sfr external Description dim MANTXPIN as sbit va i PIN as sbit Transmit line sfr external dim s dim MANRXPIN Direction as Direction of the Receive MANRX Direction as sbit sfr external pin sbit at DDRB BO dim dim MANTXPIN Direction as MANTXPIN Direction as sbit sfr external pin sbit at DDRB B1 Direction of the Transmit MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 247 CHAPTER 6 Libraries mikroBasic PRO for AVR Library Routines Man Receive Init Man Receive Man Send Init Man Send M
372. red for writing operation sectcnt number of sectors to be prepared for writing operation The corresponding ports must be appropriately initialized for CF card See Requires Cf Init initialize compact flash for writing to sector 590 Cf Write Inrt 590 1 Cf Write Byte sub procedure Cf Write Byte dim data as byte Nothing Writes a byte to Compact Flash sector buffer location currently pointed to by writing pointers These pointers will be autoicremented upon reading When sector buffer is full its content will be transfered to appropriate flash memory Description sagar Parameters data byte to be written The corresponding MCU ports must be appropriately initialized for CF card See Cf Init CF card must be initialized for writing operation See Cf Write Init dim data as byte data OxAA Cf Write Byte data MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 195 CHAPTER 6 Libraries mikroBasic PRO for AVR Cf Read Sector Prototvpe sub procedure Cf Read Sector dim sector number as longword dim byref buffer as 512 Reads one sector 512 bytes Read data is stored into buffer provided by the buffer parameter Description Parameters sector number sector to be read buffer data buffer of at least 512 bytes in length c e MCU ports must be appropriately initialized for CF card See read sector 22 dim data as array 512 of byte
373. resent reserved words that cannot be redefined for example PO 1 T1CON etc Probe Code Assistant for specific letters Ctrl Space in Editor or refer to Predefined Globals and Constants Here is the alphabetical listing of keywords in mikroBasic PRO for AVR Abstract And Array As at Asm Assembler Automated bdata Begin buit Case Cdecl Class Code compact Const Constructor Contains Data Default deprecated Destructor Dispid Dispinterface Div Do Downto Ej Ej bj Q K ct Q External Far File Finalization Finally For Forward Function Goto idata TR ilevel Implementation In Index Inherited Initialization Inline Interface LS Label large Library Message Mod name Near Nil Not Object Of on Or org Out overload Override package Packed Pascal pdata platform Private Procedure Program Property Protected Public Published Raise Read Readonly Record Register Repeat requires Reset Resourcestring Resume Safecall abut Set Sft Shi Shr small Stdead Stored String Stringresource Reintroduce Then Threadvar To Try ype Unit Until Uses Var Virtual Volatile While With Write Writeonly xdata Xor Also mikroBasic PRO for AVR includes number of predefined identifiers used in libraries You could replace them by your own definitions if you plan to develop your own libraries For more i
374. ring text and the 5 metacharacter only at the end Embedded line separators will not be matched by or 5 You may however wish to treat a string as a multi line buffer such that the will match after any line separator within the string and 5 will match before any line separator Regular expressions works with line separators as recommended at http www uni code org unicode reports tr18 Metacharacters Predefined classes vw an alphanumeric character including NW a nonalphanumeric character d a numeric character VD a non numeric character s any space same as cnr 1 S a non space You may use w a and s within custom character classes Example routi de matches strings like routile rouci e and so on but not routine routime and so on Metacharacters Word boundaries A word boundary o is a spot between two characters that has an alphanumer ic character one side and a nonalphanumeric character w on the other side in either order counting the imaginary characters off the beginning and end of the string as matching a w b match a word boundary B match non word boundary 64 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Metacharacters Iterators Any item of a regular expression may be followed by another type of metacharac ters iterators Using th
375. roject files if they are available at this point You can always add project files later using the Project Manager in IDE Add File To Project D Projects FirstProject Definit mbas GE Add File Name D Projects FirstProject Definit mbas Remove Remove All 4 Back Next gt Cancel Step Five Click Finish button to create your New Project New Project Wizard Step 5 5 You have successfully created a new project Click Finish to save the changes and to close the wizard d Cancel 4 Back Finish Related topics Project Manager Project Settings MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 71 CHAPTER 2 Environment mikroBasic PRO for AVR CUSTOMIZING PROJECTS Edit Project You can change basic project settings in the Project Settings window You can change chip and oscillator frequency Any change in the Project Setting Window affects currently active project only so in case more than one project is open you have to ensure that exactly the desired project is set as active one in the Project Manager Managing Project Group mikroBasic PRO for AVR IDE provides covenient option which enables several proj ects to be open simultaneously If you have several projects being connected in some Way you can create a project group The project group may be saved by clicking the Save Project Group Icon from the Project Manager window The pro
376. rom address 2 Soft I2C Start Issue repeated start signal Soft I2C Write 0xA1 Address PCF8583 for reading R W 1 seconds Soft I2C Read l Read seconds byte minutes Soft I2C Read 1 Read minutes byte hours Soft I2C Read 1 Read hours byte day Soft I2C 1 Read year day byte month Soft I2C Read 0 Read weekday month byte Sort I2C 0 Issue stop signal end sub MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 343 CHAPTER 6 Libraries mikroBasic PRO for AVR a a Formats date and time sub procedure Transform Time seconds seconds and OxF0 gt gt 4 10 seconds and 0 0 T Transform seconds minutes minutes and OxF0 gt gt 4 10 minutes 0 0 Transform months hours hours OxFO0 gt gt 4 10 hours and Ox0F i Transform hours year day and 0 0 gt gt 6 T Transform year day day and 0x30 gt gt 4 10 day and OxOF L Transform day month month and 0 10 gt gt 4 10 month and OxOF Transform month end sub Soe eee See SaaS ee Output values to Lcd sub procedure Display Time Led Ohr l 6 4 10 48 Print tens digit of day variable Led Chr l1 7 day mod 10 48 Print oness digit of day variable Lcd Chr 1 9 month 10 48 Lcd Chr 1 10 month mod 10 48 pos Chet 15 year T B6 Print year vaiable 8 start from year 2008
377. rrent graphic panel of Glcd at coordinates Parameters Description x dot position on x axis y dot position on y axis color color parameter Valid values SPI 6963 BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example 5 T 963C Dot xO yO poolot MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 425 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI T6963C Write Char Prototype sub procedure SPI T6963C Write Char dim c as byte dim x as byte yP dim y as byte dim mode as byte Writes a char in the current text panel of Glcd at coordinates Parameters c Char to be written x Char position on x axis y Char position on y axis node mode parameter Valid values SPI 6963 ROM MODE OR SPI 6963 ROM MODE SPI T6963C ROM MODE AND and SPI 6963 ROM MODE TEXT Mode parameter explanation Description OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in negative mode i e white text on black background AND Mode The text and graphic data shown on display are combined via the logical AND function
378. rt for working with keypad Global variables keypadPort Reg Keypad port keypadPort Reg Direction Direction of the Keypad port must be defined before using this function Initialize PORTB for communication with keypad dim keypadPort as byte at PORTB dim keypadPort Direction as byte at DDRB Keypad Init Keypad Key Press sub function Keypad Key Press as byte The code of a pressed key 1 16 If no key is pressed returns 0 Reads the key from keypad when key gets pressed Port needs to be initialized for working with the Keypad library see Keypad Init dim kp as byte kp Keypad Key Press Keypad Key Click Prototype sub function Keypad Key Click as byte The code of a clicked key 1 16 If no key is clicked returns 0 Call to Keypad Key Click is a blocking call the function waits until some key is pressed and released When released the function returns 1 to 16 depending Description on the key If more than one key is pressed simultaneously the function will wait until all pressed keys are released After that the function will return the code of the first pressed key Port needs to be initialized for working with the Keypad library see Keypad Init dim kp as byte kp Keypad Key Click MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 235 CHAPTER 6 Libraries mikroBasic PRO for AVR Library Example This is a simple example of using the Keypad L
379. rxtx pin direction direction of the RS 485 Transmit Receive pin must be defined before using this function UART HW module needs to be initialized See UARTXx Init RS485 module pinout dim RS485 rxtx pin as sbit at PORTD B2 dim RS485 rxtx pin direction as sbit at DDRD B2 End of RS485 module pinout Pass pointers to UART functions of used UART module RT Wr Ptr QUARTI Write T Rd Ptr UART1 Read UART Rdy Ptr UART1 Data Ready UART TX Idle Ptr QUART1 TX Idle UART1 Init 9600 initialize UART module RS485Slave Init 160 intialize MCU as a Slave for RS 485 communication with address 160 330 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries RS485Slave Receive sub B e RS485Slave Receive dim byref data buffer as byte 20 Receives messages from Master If Slave address and Message address field don t match then the message will be discarded Messages are multi byte so this routine must be called for each byte received Prototype Parameters data buffer 6 byte buffer for storing received data in the following manner data 2 message content 3 number of message bytes received 1 3 data 4 is set to 255 when message is received data 5 18 set to 255 if error has occurred Description 0 The function automatically adjusts 4 5 upon every received message Thes
380. s File name should be in DOS 8 3 file name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does no have to take care of that The file name and extension are case insensitive The library will convert them to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with the first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between file name and extension i e MIKROELETXT gt MIKROELE TXT In this case last 3 characters of the string are considered to be file extension Description 211 cre tcr creation and attributs flags Each bit corresponds to the appropriate file attribut Po oor 6 0x40 Device internal use only never found on disk File creation flag If the file does not exist and this flag is set a new file with specified name will be created Note Long File Names LFN are not supported MMC SD card and MMC library must be initialized for file operations See Requires Fat Init create file with archive attribut if it does not already exist Fat Assign MIKRO007 TXT O0xAO0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 263 CHAPTER 6 Libraries mikr
381. s character Deseripuon Parameters Out Char character to be written Requires Lcd needs to be initialized for SPI communication see SPI Lcd Config routines Write character e at current cursor position SPI Led Chr Cp e MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 409 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI Lcd Cmd Prototype sub procedure SPI Lcd Cmd dim out char as byte Sends command to Lcd Parameters Description out char command to be sent Note Predefined constants can be passed to the function see Available SPI Lcd Commands Lcd needs to be initialized for SP communication see SPI Lcd Config routines Clear Lcd display SPI Lcd Cmd LCD CLEAR Available SPI Lcd Commands a C Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected 2 410 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD RETURN HOME CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example This example demonstrates how to communicate Lcd via the SPI module using serial to parallel convertor 23517 program Spi Lcd dim text as char 17 Port Expander module connections dim SPExpanderRST as sbit at PORTB BO SPExpanderCS sbit at 1 SPExpanderRST Direction as sbit at DDRB BO SPExpanderCS Direction
382. s longint 100 Variables and AVR Every declared variable consumes part of RAM memory Data type of variable deter mines not only the allowed range of values but also the space a variable occupies in RAM memory Bear in mind that operations using different types of variables take different time to be completed mikroBasic PRO for AVR recycles local variable memory space local variables declared in different functions and procedures share the same memory space if possible There is no need to declare SFR explicitly as mikroBasic PRO for AVR automatically declares relevant registers as global variables of word For example 10 TMR1 etc MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 127 CHAPTER 5 Language Reference mikroBasic PRO for AVR CONSTANTS Constant is a 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 any expression but cannot be assigned a new value Constants are declared in the declaration part of the 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 valid identifier It is a tradition to write constant names in uppercase Constant requires you to specify value which is a literal appropriate for the given type type is option al and in the absence of it the compiler assumes the smallest type that
383. s word dim tmp as byte dim j as word are lexically equivalent and parse identically Newline Character Newline character CR LF is not a whitespace in BASIC and serves as a statement terminator separator In mikroBasic PRO for AVR however you may use newline to break long statements into several lines Parser will first try to get the longest pos sible expression across lines if necessary and then check for statement termina tors Whitespace in Strings The ASCII characters representing whitespace can occur within string literals where they are protected from the normal parsing process they remain as a part of the string For example statement some string mikro foo parses to four tokens including a single string literal token some string mikro foo newline character 112 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference COMMENTS Comments are pieces of text used to annotate a program and are technically anoth er form of whitespace Comments are for the programmer s use only they are stripped from the source text before parsing Use the apostrophe to create a comment Any text between an apostrophe and the end of the line constitutes a comment May span one line only There are no multi line comments in mikroBasic PRO for AVR TOKENS Token is the smallest element of a mikroBasic PRO for AVR program meaningful to the comp
384. sbit sfr external select pin as sbit DDRD B4 dim GLCD RW Direction as Direction of the dim GLCD RW Direction sbit sfr external Read Write pin as sbit DDRD B5 dim GLCD EN Direction as i i 1 EN Direction NEL Direction of the Enable pin Drs m6 dim Direction of the Reset pin GLCD RST Direction as sbit at DDRD B7 dim GLCD RST Direction as sbit sfr external 218 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Library Routines Basic routines Glcd Init Set Side Set X Glcd Set Page Gled Read Data Write Data Advanced routines Glcd Fill Dot Glcd Line Glcd V Line Glcd H Line Glcd Rectangle Box Circle Set Font Write Char Write Text Glcd Image MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 219 CHAPTER 6 Libraries mikroBasic PRO for AVR Glcd Init D Initializes the Glcd module Each of the control lines is both port and pin config escription urable while data lines must be on a single port pins lt 0 7 gt Global variables GLCD CS1 Chip select 1 signal pin GLCD CS2 Chip select 2 signal pin GLCD RS Register select signal pin GLCD_ RW Read Write Signal pin GLCD Enable signal GLCD RST Reset signal p
385. sing this function See Soft 2 Init routine I su STOP signal soft Stop MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 341 CHAPTER 6 Libraries mikroBasic PRO for AVR Soft I2C Break Description Requires All Software 12C Library functions can block the program flow see note at the top of this page Call this routine from interrupt to unblock the program execu tion This mechanism is similar to WDT Note Interrupts should be disabled before using Software 1 routins again see note at the top of this page Nothing Soft 2 pinout definition dim Soft I2C Sel Output as sbit at PORTC BO dim Soft I2C Sda Output as sbit at PORTC B1 dim Soft I2C Scl Input as sbit at PINC BO dim Soft I2C Sda Input as sbit at 1 dim Soft I2C Scl Pin Direction as sbit at DDRC BO dim Soft I2C Pin Direction as sbit at DDRC B1 of Soft I2C pinout definition dim counter as byte sub procedure Timer0Overflow ISR org 0x12 counter 0 if counter gt 20 then Soft 12 counter 0 reset counter else Inc counter increment counter end if end sub main bit Timer0 overflow interrupt enable PCCRO bit Start timer with 1024 prescaler SREG I bit Interrupt disable try Soft I2C Init with blocking prevention mechanism SREG I bit 1 Interrupt enable Soft I2C Init SREG I bit 0 Interrupt disable 342
386. specifies the Glcd side values from 0 to 63 specify the left side values from 64 to 127 specify the right side Note For side x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see SPI Glcd Init routines The following two lines are equivalent and both of them select the left side of Glcd SPI 1 Set Side 0 SPI Gled Set Side 10 SPI Glcd Set Page Prototype sub procedure SPI Glcd Set Page dim page as byte Selects page of Glcd Parameters Description i page page number Valid values 0 7 Note For side x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see SPI Glcd Init routines 392 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries SPI Glcd Set X Prototype sub procedure SPI Glcd Set X dim x pos as byte Sets x axis position to x pos dots from the left border of Glcd within the select ed side Parameters Description x pos position on x axis Valid values 0 63 Note For side x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see SPI Glcd Init routines SPI Glcd Read Data Prototype sub function SPI Glcd Read Data as byte Returns One byt
387. spud Baki pee qe Rao 453 T6963C Set Cursor 454 6963 454 T6963C DisplayTxtPanel 454 T6963C SetGrPanel 455 T6963C SetTxtPanel 455 T6963C PanelFill 2 2222222 4 42 456 169636 se sek oe et heed EPI RR needed bea dnas 456 T16963C TFI ee DER 456 6963 457 T6963C Graphles 457 Rest DM m 457 16903C CUESOF iV ee E RRERPX RR 458 T6963C Cursor 458 Library Example paces Bee TREE 458 The following drawing demo tests advanced routines 458 HW Connection csse exce Re BASSES EAE 464 TWILA ADT 465 Library Roullnies creer mech nee EG C RR UR 465 465 TWINS BUSY tco DERE ec Ue E UP qd dpa d qs 465 IWISt rt ei nemicu iiba tapunun eiia Ea a py 466 TWI Read RE eU Ra R eU TEE 466 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XXIII Table of Contents mikroBasic PRO for AVR
388. ssed the volume will not be labeled Description Note This routine can be used instead or in conjunction with the Cf Fat Init routine Note If CF card already contains a valid boot sector it will remain unchanged except volume label field and only FAT and ROOT tables will be erased Also the new volume label will be set Requires Nothing format and initialize the FAT library if Cf Fat QuickFormat mikroE 0 then end if MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 197 CHAPTER 6 Libraries mikroBasic PRO for AVR Cf Fat Assign Prototype sub function Cf Fat Assign dim byref filename as char 12 dim file cre attr as byte as byte 0 if file does not exist and no new file is created 1 if file already exists or file does not exist but a new file is created Assigns file for file operations read write delete All subsequent file opera tions will be applied to the assigned file Parameters filename name of the file that should be assigned for file operations The file name should be in DOS 8 3 file name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does not have to take care of that The file name and extension are case insensitive The library will convert them to the proper case automatically so the user does not h
389. st 3 characters of the string are considered to be file extension file attr file creation and attributs flags Each bit corresponds to the appropriate file attribut MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Libraries 203 CHAPTER 6 Libraries mikroBasic PRO for AVR Bi Wak Been A 6 0x40 Device internal use only never found on disk Note Long File Names LFN are not supported CF card and CF library must be initialized for file operations See Cf Fat Init Try to create a swap file with archive atribute whose size will be at least 1000 sectors t If it succeeds it sends the No of start sec tor over USART dim size as longword main size Cf Fat Get Swap File 1000 mikroE txt 0x20 if size then UART1 Write OxAA UART1 Write Lo size UART1 Write size UART1 Write Higher size UARTI Write Highest size UART1 Write 0xAA end if end 204 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Library Example CHAPTER 6 Libraries The following example is a simple demonstration of CF Compact Flash Library which shows how to use CF card data accessing routines program CF Fatl6 Test dim set compact flash pinout Cf Data Port as byte at PORTD Cf Data Port Direction as byte at DDRD CF RDY CF WE CF OE CF 1 CF CE1 CF A2
390. sub only for the sake of backward compatibility It is better to rely on functions and procedures creating legible structured programs 162 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference ASM STATEMENT mikroBasic PRO for AVR allows embedding assembly in the source code by means of the asm statement Note that you cannot use numerals as absolute addresses for register variables in assembly instructions You may use symbolic names instead listing will display these names as well as addresses You can group assembly instructions with the asm keyword asm block of assembly instructions end asm mikroBasic PRO comments are not allowed in embedded assembly code Instead you may use one line assembly comments starting with semicolon If you plan to use a certain mikroBasic PRO variable in embedded assembly only be sure to at least initialize it assign it initial value in mikroBasic PRO code otherwise the linker will issue an error This is not applied to predefined globals such as PO For example the following code will not be compiled because the linker won t be able to recognize the variable myvar program test dim myvar as word main asm MOV 10 WO MOV WO myvar end asm end Adding the following line or similar above the asm block would let linker know that variable is used myvar 20 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIO
391. t Ow Write 0xCC T Ow Write 0xBE Issue command Issue command temp temp Ow Read Ow Read lt lt 8 temp CHAPTER 6 Libraries signal SKIP ROM CONVERT T SKIP ROM READ SCRATCHPAD Format and display result on Lcd Display Temperature temp Delay ms 520 287 CHAPTER 6 Libraries mikroBasic PRO for AVR HW Connection 1259 GND XTAL1 vc T gt o LCD 2X16 Example of 051820 connection 288 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR PORT EXPANDER LIBRARY CHAPTER 6 Libraries The mikroBasic PRO for AVR provides a library for communication with the Microchip s Port Expander 23517 via SPI interface Connections of the AVR compliant MCU and 23517 is given on the schematic at the bottom of this page Note Library uses the SPI module for communication The user must initialize SPI module before using the Port Expander Library Note Prior to calling any of this library routines Spi Rd Ptr needs to be initialized with the appropriate SPI Read routine Note Library does not use Port Expander interrupts External dependencies of Port Expander Library The following variables must be defined in all projects using Port Expander Library dim SPI sbit s dim SPI sbit dim on as fr external t PORTB BO ExpanderRST Directi sbit sfr external di
392. t lt FILE gt Lib Example lt FILE gt lt TYPE gt REGULAR lt TYPE gt lt LIB gt 8 Add Library to mlk file for each MCU that you want to use with your library 9 Click Refresh button in Library Manager 10 Example Library should appear in the Library manager window MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Environment 85 CHAPTER 2 Environment mikroBasic PRO for AVR Multiple Library Versions Library Alias represents unique name that is linked to corresponding Library mcl file For example UART library for 16 is different from UART library for ATMEGA128 MCU Therefore two different UART Library versions were made see files for these two MCUs Note that these two libraries have the same Library Alias UART in both mlk files This approach enables you to have identical repre sentation of UART library for both MCUs in Library Manager Note In the Uses folder there should be two subfolders LTE64kKW and GT64kW depending on the Flash memory size of the desired MCU See AVR Specifics for a detailed information regarding this subject Related topics Library Manager Project Manager Managing Source Files 86 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER mikroBasic PRO for AVR Specifics The following topics cover the specifics of mikroBasic PRO for AVR compiler Basic Standard Issues Predefine
393. t 1 1 txt 0 LCD Out 2 1 txt 1 delay_ms 1000 Lcd Cmd i LCD Out 1 1 txt 1 LCD Out 2 4 txt 2 delay_ms 500 end main EJ If you place a mouse cursor over the tooltip box the collapsed text will be shown in a tooltip style box main gt 2 main PORTA 0 PORTB 0 Led Init LCD Out 1 1 txt 0 LCD Out 2 1 txt 1 delay_ms 1000 Lcd 1 LCD Out i1 1 txt 1 LCD Out 2 4 txt 2 delay 500 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 37 CHAPTER 2 Environment mikroBasic PRO for AVR Parameter Assistant The Parameter Assistant will be automatically invoked when you open parenthesis or press Shift Ctrl Space If the name of a valid function precedes the parenthe sis then the expected parameters will be displayed in a floating panel As you type the actual parameter the next expected parameter will become bold channel byte ADC Rea Code Templates Auto Complete You can insert the Code Template by typing the name of the template for instance whiles then press Ctrl J and the Code Editor will automatically generate a code You can add your own templates to the list Select Tools Options from the drop down menu or click the Show Options Icon and then select the Auto Complete Tab Here you can enter the appropriate keyword description and code of your template Autocomplete macros can retreive system and project information D
394. t as string 10 input 12345678 IsntTob5trirnput Ext eze ge 12345678 480 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries LongWordToStr Prototype sub procedure LongWordToStr dim input as longword dim byref out put as stringi 9 Converts input double word number to a string The output string is right justi fied and the remaining positions on the left if any are filled with blanks Description Parameters input double word number to be converted output destination string dim input as longint txt as stringi 9 input 12345678 IsntToStrirnput Ext r Ext 12345618 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 481 CHAPTER 6 Libraries mikroBasic PRO for AVR FloatToStr sub function FloatToStr dim input as real dim byref output as Prototype stringi 221 3 if input number is NaN 2 if input number is INF 1 if input number is INF 0 if conversion was successful Converts a floating point number to a string Parameters input floating point number to be converted Description output destination string The output string is left justified and null terminated after the last digit Note Given floating point number will be truncated to 7 most significant digits before conversion dim ffl ff2 ff3 as real txt as string 22 ffl 374 2 ff2 123 456789
395. t filtering schemes to limit incoming packets It also provides an internal DMA module for fast data throughput and hardware assisted IP checksum calcula tions Communication with the host controller is implemented via two interrupt pins and the with data rates of up to 10 Mb s Two dedicated pins are us link and network activity indication This library is designed to simplify handling of the underlying hardware 1 ed for LED ENC28J60 It works with any AVR MCU with integrated SPI and more than 4 Kb ROM memory SPI Ethernet library supports IPv4 protocol ARP requests ICMP echo requests UDP requests TCP requests no stack no packet reconstruction packet fragmentation is NOT supported Note Prior to calling any of this library routines Spi_Rd_Ptr needs to be initialized with the appropriate SPI Read routine Note The appropriate hardware SPI module must be initialized before using any of the SPI Ethernet library routines Refer to SPI Library MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 367 CHAPTER 6 Libraries External dependencies of SPI Ethernet Library The following variables must be defined in all projects using SPI Eth ernet Library dim SPI Ethernet CS as sbit sfr external dim SPI Ethernet RST as sbit sfr external dim Description ENC28J60 chip select pin ENC28J60 reset pin SPI Ethernet CS Direc Direction of
396. t in hazardous environments requiring fail safe performance such as in the operation of nuclear facilities aircraft navigation or communication systems air traffic control direct life support machines or weapons sys tems in which the failure of the Software could lead directly to death personal injury or severe physical or environmental damage High Risk Activities mikroElektronika and its suppliers specifically disclaim any express or implied warranty of fitness for High Risk Activities LICENSE AGREEMENT By using the mikroBasic PRO for AVR compiler you agree to the terms of this agreement Only one person may use licensed version of mikroPascal for 8051 compiler at a time Copyright mikroElektronika 2003 2009 This manual covers mikroBasic PRO for AVR version 1 2 and the related topics Newer versions may 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 at the address office mikroe com Please include next information in your bug report Your operating system Version of mikroBasic PRO for AVR Code sample Description of a bug CONTACT US mikroElektronika Voice 381 11 36 28 830 Fax 381 11 36 28 831 Web www mikroe com E mail office mikroe com Windows is a Registered trademark of Microsoft Corp All other trade
397. t suitable for mobile applications such as PDAs MP3 players or mobile measurement equip ment Although small this contoller has a capability of displaying and merging text and graphics and it manages all the interfacing signals to the displays Row and Col umn drivers For creating a custom set of Glcd images use Glcd Bitmap Editor Tool Note ChipEnable CE FontSelect FS and Reverse MD have to be set to appro priate levels by the user outside of the T6963C Init function See the Library Exam ple code at the bottom of this page Note Some mikroElektronika s adapter boards have pinout different from T6369C datasheets Appropriate relations between these labels are given in the table below Adapter Board T6369C datasheet 442 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR CHAPTER 6 Libraries External dependencies of T6963C Graphic Lcd Library The following variables must be defined in all projects using T6963C e Lcd library T6963C dataPort as s byte sfr external T6963C Data Port T6963C Control Port i i T9620 etri Write signal pan Read signal dim T6963C ctrl din sbit at PORTC B1 dim T6963C 1 Command Data signal 512 Reset signal T6963 ctrlPoet as ea sfr external dim T6963C ctrlwr as Sbit sfr external dim T6963C ctrlrd as sbit sfr external dim T6963C ctrlcd as Sbit sfr external dim 6963 ctrlrst as sbit sfr external dim T6
398. t to reverse engineer decompile or disassemble it except and only to the extent that such activity is expressly permitted by applicable law notwithstanding this limitation If you have purchased an upgrade version of Software it constitutes a single prod uct with the mikroElektronika Associates software that you upgraded You may use the upgrade version of Software only in accordance with the License Agreement 4 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroBasic PRO for AVR Introduction LIMITED WARRANTY Respectfully excepting the Redistributables which are provided as is without war ranty of any kind mikroElektronika Associates warrants that Software once updat ed and properly used will perform substantially in accordance with the accompany ing documentation and Software media will be free from defects in materials and workmanship for a period of ninety 90 days from the date of receipt Any implied warranties on Software are limited to ninety 90 days mikroElektronika Associates and its suppliers entire liability and your exclusive remedy shall be at mikroElektronika Associates option either a return of the price paid or b repair or replacement of Software that does not meet mikroElektronika Associates Limited Warranty and which is returned to mikroElektronika Associates with a copy of your receipt DO NOT RETURN ANY PRODUCT UNTIL YOU HAVE CALLED MIKROELEKTRONIKA ASSOCI
399. t2 LED Out 2 6 txt4 Delay ms 2000 Out 1 1 txtl LCD Out 2 4 txt2 Delay ms 500 Moving text for i 0 to 3 Lcd Cmd LCD CLEAR Lcd Cmd LCD CURSOR OFF Lcd Cmd LCD CLEAR Y Initialize Lcd Clear Write Write Clear Write Write display Cursor orf text in text in display text in text in first row second row first row second row Move text to the right 4 times MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 245 CHAPTER 6 Libraries Lcd Cmd LCD SHIFT RIGHT Move Delay next i while TRUE for i 0 to 6 Lcd Cmd LCD SHIFT LEFT Move Delay next i for i 0 to 6 Lcd Cmd LCD SHIFT RIGHT Move Delay next i wend end OSCILLATOR mikroBasic PRO for AVR Endless loop Move text to the left 7 times Move text to the right 7 times VCC Q r o CT LCD 2 16 9LVOANLV E Lcd HW connection 246 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries MANCHESTER CODE LIBRARY The mikroBasic PRO for AVR provides a library for handling Manchester coded sig nals The Manchester code is a code in which data and clock signals are combined to form a single self synchronizing data stream each encoded bit contains a transi tion at the midpoint of a bit period the di
400. ta for registers as byte 16 buffer for CID and CSD registers Display byte in hex sub procedure printhex dim i as byte dim bHi bLo as byte bHi i and 0 0 High nibble bHi bHi gt gt 4 bHi bHi 0 if bHi gt 9 then bHi bHi 7 end if bLo i and OxOF 0 Low nibble if bLo gt 9 then bLo bLot7 end if UART1 Write bHi UART1 Write bLo end sub main DDRC 255 PORTC 0 SIFDEF RS232 debug UART1_Init 19200 SENDIF Delay 10 DDRA 255 PORTA 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 273 CHAPTER 6 Libraries mikroBasic PRO for AVR SIFDEF RS232 debug UARTI Write Text AVR Started If AVR present report UART1 Write 13 UART1 Write 10 SENDIF Beffore all we must initialise a MMC card SPI1 Init Advanced SPI MASTER SPI FCY DIV2 SPI LO LEAD ING Spi Rd Ptr 5 1 Read i c Mme cnam PORTC i SIFDEF RS232 debug if i 0 then UARTI Write Text MMC Init OK If MMC present report UART1 Write 13 UART1 Write 10 end if if i then UARTI Write Text MMC Ixnzit error If error report VARTI Write 13 UART1 Write 10 end if SENDIF for i 0 to 511 dData i E Fill MMC buffer with same characters next i i Mmc Write Sector 55 dData SIFDEF RS232 debug if i 0 then UART1 Write Text Write OK else if there are errors VARTI
401. tarting address of a routine in ROM It is appended to the declaration of routine For example sub procedure proc dim par as word org 0x200 Procedure will start at the address 0x200 end sub Note You must specify an even address when using the directive 94 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroBasic PRO for AVR Specifics BUILT IN ROUTINES The mikroBasic PRO for AVR compiler provides a set of useful built in utility func tions The Hi Higher Highest routines are implemented as macros If you want to use these functions you must include built in h header file located in the ini clude folder of the compiler into your project The Delay us and Delay ms routines are implemented as inline i e code is gen erated in the place of a call so the call doesn t count against the nested call limit The vdelay ms Delay and Get Fosc kHz are actual Basic routines Their sources can be found in Delays mbas file located in the uses folder of the compiler Lo Hi Higher Highest Inc Dec Delay_us Delay_ms Vdelay_ms Delay_Cyc Clock_Khz Clock_Mhz SetFuncCall MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 95 CHAPTER 3 Specifics mikroBasic PRO for AVR 96 Prototype sub function Lo number as longint as byte Returns Lowest 8 bits byte of number bits 7 0 Function returns the lowest byte o
402. te Initializes the Lcd module via SPI interface RT Parameters Description DeviceAddress spi expander hardware address see schematic at the bottom of this page Global variables SPExpandercs Chip Select line SPExpanderRST Reset line R SPExpanderCS Direction Direction of the Chip Select pin equires cM E SPExpanderRST Direction Direction of the Reset pin must be defined before using this function SPI module needs to be initialized See SPI1 Init and SPI1 Init Advanced routines port expander pinout definition dim SPExpanderCS as sbit at PORTB B1 SPExpanderRST as sbit at PORTB BO SPExpanderCS Direction as sbit at DDRB B1 SPExpanderRST Direction as sbit at DDRB BO If Port Expander Library uses SPI1 module Tnit Initialize SPI module used with PortExpander Spi Rd Ptr SPI1 Read Pass pointer to SPI Read func tion of used SPI module SPI Lcd Config 0 initialize lcd over spi inter face MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 407 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI Lcd Out Prototvpe sub procedure SPI Lcd Out dim row as byte dim column as byte yp dim byref text as string 20 Description Requires Prints text on the Lcd starting from specified position Both string variables and literals can be passed as a text Parameters row Starting position row number column Starting position column num
403. te size as longint buffer as byte 512 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 275 CHAPTER 6 Libraries mikroBasic PRO for AVR Writes string to USART sub procedure Write Str dim byref ostr as byte 2 dim i as byte i 0 while ostr 1 UART1_ Write 1 UART1_ Write 0 end sub ew 0 osti x sub procedure Create New File filename 7 tests Fat Assign filename 0 0 ate file Mmc Fat Rewrite new data for loop card UART1 Write file contents 0 loop div 10 file contents 1 loop 10 4 Mmc Fat Write file contents 42 file next loop end sub 1 to 99 Creates many new files sub procedure Create Multiple Files for loop2 to Z UART1 Write loop2 the performance filename 7 loop2 Mmc Fat Assign filename ate a new one Mmc Fat Rewrite with new data for loop 1 to 44 file contents 0 file comtents 1 Mmc Fat Write file contents 0 0 42 file next loop next loop2 end sub 11 Creates new file and writes some data to it Set filename for single file Will not find file and then cre To clear file and start with We want 5 files on the MMC 48 48 write data to the assigned and writes data to them this line can slow down set filename find existing file or cre To clear file and start byte loop div 10 48 byte loop mo
404. te 17 buffer mikroElektronika Spi Ethernet putBytes buffer 16 put an RAM array into 28060 buffer MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 375 CHAPTER 6 Libraries mikroBasic PRO for AVR Spi Ethernet putConstBytes sub procedure Spi Ethernet putConstBytes const ptr as byte dim Prototype zT p _p y p yte This is MAC module routine It stores requested number of const bytes into ENC28760 RAM starting from current 28760 write pointer EwRPT location Description Parameters ptr const buffer containing bytes to be written into x c28560 RAM n humber of bytes to be written Ethernet module has to be initialized See Spi Ethernet Init const buffer as byte 17 buffer mikroElektronika Spi Ethernet putConst Bytes butter 16 put a const array into 28060 buffer Spi Ethernet putString Prototype sub function Spi Ethernet putString dim ptr as byte as word Returns Number of bytes written into c28560 RAM This is MAC module routine It stores whole string excluding null termination into ENC28760 RAM starting from current xc28560 write pointer wRPT location Deseription Parameters ptr String to be written into ENC28J60 RAM Ethernet module has to be initialized See Spi_Ethernet_Init dim buffer as string 16 buffer mikroElektronika Spi Ethernet putString buffer
405. that the parameter step value may be negative allowing you to create countdown Here is an example of calculating scalar product of two vectors and of length n using the for statement S for ll Eee Q to mel I i next i Endless Loop The for statement results an endless loop if final value equals or exceeds the range of the counter 5 type 156 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference WHILE STATEMENT Use the while keyword to conditionally iterate a statement The syntax of the while statement is while expression statements wend statements are executed repeatedly as long as expression evaluates true The test takes place before statements are executed Thus if expression evaluates false on the first pass the loop does not execute is an example of calculating scalar product of two vectors using the while statement 5 0 ME while i n bf i is Tl Probably the easiest way to create an endless loop is to use the statement while TRUE wend MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 157 CHAPTER 5 Language Reference mikroBasic PRO for AVR 158 DO STATEMENT The do statement executes until the condition becomes true The syntax of the do statement is do statements loop until expression
406. the first 1 words of the strings s1 and s2 and returns a value indicating their relationship Meaning si less than s2 Description sl equal to s2 51 greater than 52 The value returned by the function is determined by the difference between the values of the first pair of words that differ in the strings being compared within first len words strncpy Prototype iei iie strncpy dim byref 51 52 as string 100 dim size The function copies at most size characters from the string 52 to the string 51 Description s2 contains fewer characters than size s1 is padded out with null characters up to the total length of the size characters strpbrk Prototype sub function strpbrk dim byref 51 52 as string 100 as word The function searches 51 for the first occurrence of any character from the string 52 The null terminator is not included in the search The function returns an index of the matching character in 1 If si contains no characters from 52 the function returns 0xFFFF Description strrchr Prototype strrchr dim byref s as stringi 100 dim ch as byte The function searches the string 5 for the last occurrence of the character ch The null character terminating s is not included in the search The function returns an index of the last ch found in s if no matching character was found the function returns 0xFFFF Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS
407. the media where the user can freely write read data It s main purpose in the mikroBasic PRO for AVR s library is to be used for fast data acquisition when the time critical acquisition has finished the data can be re written into a normal file and formatted in the most suitable Parameters sectors cnt number of consecutive sectors that user wants the swap file to have filename name of the file that should be assigned for file operations File name should be in DOS 8 3 file name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does no have to take care of that The file name and extension are case insensitive The library will convert them to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with the first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between file name and extension i e MIKROELETXT gt MIKROELE TXT In this case last 3 characters of the string are considered to be file extension file attr file creation and attributs flags Each bit corresponds to the appropriate file attribut MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 271 CHAPTER 6 Libraries mikroBasic PRO for AVR pp eec
408. the program program MyProject main procedure main Place program code here end Other than comments nothing should precede the keyword program After the pro gram name you can optionally place the include clauses Place all global declarations constants variables labels routines structures before the label main Other Modules Modules other than main start with the keyword module Newly created blank mod ule contains the bare bones module MyModule implements end Other than comments nothing should precede the keyword module After the mod ule name you can optionally place the include clauses Interface Section Part of the module above the keyword implements is referred to as interface sec tion Here you can place global declarations constants variables labels routines structures for the project Do not define routines in the interface section Instead state the prototypes of rou tines from implementation section that you want to be visible outside the module Prototypes must exactly match the declarations MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 125 CHAPTER 5 Language Reference mikroBasic PRO for AVR Implementation Section Implementation section hides all the irrelevant innards from other modules allowing encapsulation of code Everything declared below the keyword implements is private i e has its scope lim ited to the file When you declare an iden
409. then deleted sub procedure Delete File filename 7 Mmc Fat Assign filename 0 Mme Fat Delete end sub MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 277 CHAPTER 6 Libraries mikroBasic PRO for AVR Tests whether file exists and if so sends its cre ation date and file size via USART sub procedure Test File Exist dim fsize as longint year as word month day hour minute as byte outstr as bytel 12 filename 7 B if Mmc Fat Assign filename 0 0 then file has been found get its date Mmc Fat Get File Date year month day hour minute WordToStr year outstr Write Ste oubkstr ByteToStr month outstr Write Str outstr WordToStr day outstr Write Sbtr outstr WordToStr hour outstr Write WordToStr minute outstr Write Strooubstr get file size fsize Mmc Fat Get File Size hongZntToStr fsize outstr Write Str outstr else file was not found signal it UART1 Write 0x55 Delay ms 1000 UART1 Write 0x55 end if end sub Tries to create swap file whose size will be at least 100 d sectors see Help for details sub procedure M Create Swap File dim 1 as word for i 0 to 511 Buffer i i next i size Mmc Fat Get Swap File 5000 mikroE txt 0x20 see help on this sub function for details 278 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS
410. tialize the SPI module before using the SPI Lcd Library Note This Library is designed to work with mikroElektronika s Serial Lcd Glcd Adapter Board pinout see schematic at the bottom of this page for details External dependencies of SPI Lcd Library The implementation of SPI Lcd Library routines is based on Port Expander Library routines Prior to calling any of this library routines Spi Rd Ptr needs to be initialized with the appropriate Read routine External dependencies are the same as Port Expander Library external dependen cies Library Routines SPI Lcd8 Config SPI Out SPI Out Cp SPI Lcd8 Chr SPI Chr SPI MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 413 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI Lcd8 Config Prototype sub procedure SPI Lcd8 Config dim DeviceAddress as byte Description Initializes the Lcd module via SPI interface Parameters DeviceAddress Spi expander hardware address see schematic at the bottom of this page Global variables SPExpandercs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin SPExpanderRST Direction Direction of the Reset pin must be defined before using this function SPI module needs to be initialized See SPI1 Init and SPI1 Init Advanced routines port expander pinout definition dim SP
411. tialized for file operations See Fat Init The file must be previously assigned See Mmc Fat Assign open file for writing Mmc Fat Rewrite MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 265 CHAPTER 6 Libraries mikroBasic PRO for AVR Mmc Fat Append Prototype sub procedure Mmc Fat Append Nothing Opens the currently assigned file for appending Upon this function execution Description file pointers will be positioned after the last byte in the file so any subsequent file write operation will start from there MMC SD card and MMC library must be initialized for file operations See Fat Init The file must be previously assigned See Mmc Fat Assign open file for appending Mmc Fat Append Mmc Fat Delete Prototype sub procedure Mmc Fat Delete Nothing Description Deletes currently assigned file from MMC SD card MMC SD card and MMC library must be initialized for file operations See Fat Init The file must be previously assigned See Mmc Fat Assign delete current fil Mmc Fat Delete 266 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Mmc Fat Write Prototype Description sub procedure Mmc Fat Write dim byref fdata as byte 512 dim data len as word Nothing Writes requested number of bytes to the currently assigned file opened for writing Parameters
412. tifier in the implementation section of a module you cannot use it outside the module but you can use it in any block or rou tine defined within the module By placing the prototype in the interface section of the module above the imple ments you can make the routine public i e visible outside of module Prototypes must exactly match the declarations 126 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference VARIABLES Variable is an object whose value can be changed during the runtime Every vari able is declared under unique name which must be a valid identifier This name is used for accessing the memory location occupied by the variable Variables are declared in the declaration part of the file or routine each variable needs to be declared before it is used Global variables those that do not belong to any enclos ing block are declared below the include statements above the label main Specifying a data type for each variable is mandatory mikroBasic PRO syntax for variable declaration is dim identifier list as type Here identifier list is a comma delimited list of valid identifiers and type can be any data type For more details refer to Types and Types Conversions For more information on variables scope refer to the chapter Scope and Visibility Here are a few examples dim i j k byte dim counter temp as word dim samples a
413. tion You can use goto to break out from any level of nested control structures Never jump into a loop or other structured statement since this can have unpredictable effects The use of goto statement is generally discouraged as practically every algorithm can be realized without it resulting in legible structured programs One possible application of the goto statement is breaking out from deeply nested control struc tures for i to for j 0 tom if disaster goto Error end if next j next i Error error handling code MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 161 CHAPTER 5 Language Reference mikroBasic PRO for AVR GOSUB STATEMENT Use the gosub statement to unconditionally jump to a local label for more infor mation refer to Labels The syntax of the gosub statement is gosub label name label name return This will transfer control to the location of a local label specified by label name Also the calling point is remembered Upon encountering the return statement program execution will continue with the next statement line after gosub gosub line can come before or after the label It is not possible to jump into or out of routine by means of gosub Never jump into a loop or other structured statement since this can have unpredictable effects Note Like with goto the use of gosub statement is generally discouraged mikroBasic PRO for AVR supports go
414. tion process faster If your distributor is not on the list then select Other and type in distributor s email address in the box below Step 4 Press the SEND button to send key request default email client will open with ready to send message Note If email client does not open you may copy text of the message and paste it manually into a new email message before sending it to your distributor s email Marko Jovanovic Enter your address Enter invoice number if available in the Form ee KENN It DT XM ITINERE oscars _ key mikroe com Y E Mail marko mikroe com Product key 515C 557269 6F6D72 5C5E MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 9 CHAPTER 1 Introduction mikroBasic PRO for AVR This will start your e mail client with message ready for sending Review the infor mation you have entered and add the comment if you deem it necessary Please do not modify the subject line Upon receiving and verifying your request we will send the license key to the e mail address you specified in the form After Receving the License Key The license key comes as a small autoextracting file just start it anywhere on your computer in order to activate your copy of compiler and remove the demo limit You do not need to restart your computer or install any additional components Also there is no need to run the
415. ts to assigned file end sub H 27 it to USART sub procedure Open File Read filename 7 pM Cf Fat Assign filename 0 Cf Fat Reset size size of file while size gt 0 Cf Fat Read character UART1 Write character Dec size wend end sub Opens an existing file Deletes a file be created 3 and then deleted sub procedure Delete File filename 7 MEM Fat Assign filename Cf Delete end sub 0 Tests whether file exists ation date t and file size via USART MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD for mikroElektronika 2005 i To read file If file doesn t exist CHAPTER 6 Libraries Set filename for single file tests 48 48 data to the assigned file appends data to it stamp Prepare file LF Write data reads data from it and puts sub procedure returns Write data to USART rt will first and if so sends its cre 207 CHAPTER 6 Libraries mikroBasic PRO for AVR sub procedure Test File Exist dim fname as byte dim fsize as longint year as word month day hour minute as byte outstr as bytef 12 filename 7 B uncomment this line to search for file that DOES exists filename 7 uncomment this line to search for file that DOES NOT exist if Cf Fat Assign filename 0 lt gt 0 then file has been found get its date Cf Fat Get File Date year month day hour minute
416. ty sets duty ratio from 0 to 255 PWM signal graphs and formulas are shown below PHASE f i o MODE N 510 255 t Duty Ratio Description Non Inverted Inverted 312 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries FAST f 2 fax i o MODE 256 255 t Duty Ratio y 4 aa 4 4 tew M 2tew M 3 tewm 4 tew M 5 tew M 6trun 7 tewm Description Non Inverted Inverted The variable represents the prescaler factor 1 8 64 256 or 1024 Some modules also support 32 and 128 prescaler value but for this you will need to check the datasheet for the desired MCU PWMA1 Init must be called before using other functions from PWM Library You need a CMO on the given MCU that supports PWM Before calling this routine you must set the output pin for the PWM according to the datasheet DDRD 7 1 set PORTD pin 7 as output for the This code oxample is for ATmega16 second PWM module for different MCU please consult datasheet for the correct pinout of the PWM module or modules Initialize PWM module PWM1 Init PWM1 FAST MODE PWM1 PRESCALER 8 PWM1 NON INVE 127 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 313 CHAPTER 6 Libraries mikroBasic PRO for AVR PWMA1 Set Duty Prototype sub procedure PWM1 Set D
417. ue of any field by double clicking it o V P AMA AOGOI EDEDUJIOEEIIEISLIUEEBIIOADIGDLELCOCOLEAI GECCALAAG 22 MI RAM History MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 83 CHAPTER 2 Environment mikroBasic PRO for AVR SOFTWARE SIMULATOR OPTIONS m Function Toolbar Description Key Icon Start Software Simulator F9 Run Pause Eh Run or pause Software Simulator F6 Stop Software Simulator Ctrl F2 Toggle breakpoint at the current cursor position To view all breakpoints select Run View Break points from the drop down menu Double clicking F5 an item in the Breakpoints Window List locates the breakpoint Execute all instructions between the current Bun to cursor F4 instruction and cursor position Execute the current Basic single or multi cycle instruction then halt If the instruction is a routine F7 SE call enter the routine and halt at the first instruc tion following the call Execute the current Basic single or multi cycle instruction then halt F8 Execute all remaining instructions in the current routine return and then halt Related topics Run Menu Debug Toolbar 84 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR CHAPTER 2 CREATING NEW LIBRARY mikroBasic PRO for AVR allows you to create your own librar
418. ugh there are circumstances under which an object becomes temporarily hidden by the appearance of a duplicate identifier the object still exists but the original identifier cannot be used to access it until the scope of the duplicate identifier is ended Technically visibility cannot exceed scope but scope can exceed visibility MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 123 CHAPTER 5 Language Reference mikroBasic PRO for AVR MODULES In mikroBasic PRO for AVR each project consists of a single project file and one or more module files The project file with extension mbpav contains information on the project while modules with extension mbas contain the actual source code See Program Organization for a detailed look at module arrangement Modules allow you to break large programs into encapsulated modules that can be edited separately create libraries that can be used in different projects distribute libraries to other developers without disclosing the source code Each module is stored in its own file and compiled separately compiled modules are linked to create an application To build a project the compiler needs either a source file or a compiled module file for each module Include Clause mikroBasic PRO for AVR includes modules by means of the include clause It con sists of the reserved word include followed by a quoted module name Extension of the file should not be included
419. ule needs to be initialized See the T6963C Init routine T6963C SetPtr Prototype sub procedure 6963 SetPtr dim p as word dim c as byte Sets the memory pointer p for command c Description Parameters p address where command should be written c command to be written Toshiba Glcd module needs to be initialized See the 6963 Init routine T6963C SetPtr T6963C grHomeAddr start T6963C ADDRESS POINTER SET T6963C WaitReady Prototype sub procedure T6963C WaitReady Pools the status byte and loops until Toshiba module is ready Toshiba Glcd module needs to be initialized See the 6963 Init routine 000000 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 447 CHAPTER 6 Libraries mikroBasic PRO for AVR T6963C Fill Prototype sub procedure 6963 Fill dim v as byte dim start len as word Fills controller memory block with given byte Parameters Description v byte to be written start Starting address of the memory block 1en length of the memory block in bytes Toshiba Glcd module needs to be initialized See the T6963C Init routine wes T6963C Dot Prototype sub procedure T6963C Dot dim x y as integer dim color as byte Draws a dot in the current graphic panel of Glcd at coordinates Parameters Description x dot position on x axis y
420. um numerical results Since the operators are technically bytes they can be also used as unsigned operands in arithmetic operations All arithmetic operators associate from left to right Operator Operation Operands byte short word short word is addition integer longint integer longint longword float longword float byte short word subtraction multiplication division rounds down to near est integer modulus returns the remainder integer longword longint float byte short word integer longword longint float byte short word integer longword longint float byte short word integer longword longint byte short word integer byte short word integer longword longint float word integer longint float longword byte short word integer longword longint byte short word integer longint of integer division cannot be used with floating points longword longword division floating point Division by Zero If O zero is used explicitly as the second operand i e x div 0 the compiler will report an error and will not generate code But in case of implicit division by zero x div where y is 0 zero the result will be the maximum integer i e 255 if the result is byte type 65536 if the result is word type etc Unary Ar
421. up Close the active project Close project group Add project to the project group Remove project from the project group Add file to the active project Remove selected file from the project Build the active project E a a a E Run mikroElektronika s Flash programmer For details about adding and removing files from project see Add Remove Files from Project Related topics Project Settings Project Menu Options File Menu Options Project Toolbar Build Toolbar Add Remove Files from Project MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment PROJECT SETTINGS WINDOW Following options are available in the Project Settings Window Device select the appropriate device from the device drop down list Oscillator enter the oscillator frequency value Value 10 000000 MHz Related topics Project Manager MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 43 CHAPTER 2 Environment mikroBasic PRO for AVR LIBRARY MANAGER Library Manager enables simple handling libraries being used in a project Library Manager window lists all libraries extencion mci which are instantly stored in the compiler Uses folder The desirable library is added to the project by selecting check box next to the library name In order to have all library functions accessible simply pr
422. using seri al to parallel convertor MCP23S17 program SPI Glcd include bitmap Port Expander module connections dim SPExpanderRST as sbit at 0 SPExpanderCS as sbit at PORTB 1 SPExpanderRST Direction as sbit at DDRB 0 SPExpanderCS Direction sbit at DDRB 1 End Port Expander module connections dim someText as char 20 counter as byte sub procedure Delay2S delay ms 2000 end sub 402 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries main If Port Expander Library uses SPI1 module 5 1 Init Advanced SPI MASTER SPI DIV2 SPI HI TRAIL ING Initialize SPI module used with PortExpander Rd Ptr GSPII Read Pass pointer to SPI Read sub function of used SPI module If Port Expander Library uses SPI2 module i SPI2_Init_Advanced _SPI_MASTER SPI FCY DIV2 SPI HI TRAILING Initialize SPI module used with PortExpander Spi Rd Ptr amp SPI2 Read Pass pointer to SPI Read sub function of used SPI module SPI Glod Init 0 Initialize Clea via SPI SPI Gled Fill 6x00 Clear Gled while TRUE SPI Glcd Image Gtruck Draw image Delay2s Delay2s SPI Gled Fill 0x00 Clear Glod Delay2s SPI 62 40 124 56 1 Draw box SPI Cled Rectangle 5 5 84 35 1 Draw rectangle SPI Cled Line 0 63 127 0 1 Draw line Delay2s counter
423. ut parameters You can replace any line of code with a single identifier alias Symbols when prop erly used can increase code legibility and reusability Symbols need to be declared at the very beginning of the module right after the module name and optional include clauses Check Program Organization for more details Scope of a symbol is always limited to the file in which it has been declared Symbol is declared as symbol alias code Here alias must be a valid identifier which you will use throughout the code This identifier has a file scope The coae can be any line of code literals assignments function calls etc Using a symbol in the program consumes no RAM the compiler will simply replace each instance of a symbol with the appropriate line of code from the declaration Here is an example symbol MAXALLOWED 216 Symbol as alias for numeric value symbol PORT Symbol as alias for SFR symbol MYDELAY Delay ms 1000 Symbol as alias for procedure call dim cnt as byte Some variable UCET main if cnt MAXALLOWED then cnt 0 PORT 1 0 MYDELAY end if Note Symbols do not support macro expansion in a way the C preprocessor does 130 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference FUNCTIONS AND PROCEDURES Functions and procedures collectively referred to as routines are subprograms self con tai
424. ute 0 123 external volatile register sfr procedures declarations sub procedure procedure name local declarations end sub functions declarations sub function function name as return type local declarations end sub Roc ox x dox Xx Ree eee SSS olm oed xod Edd Program body main write your code here end 120 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroBasic PRO for AVR Language Reference Organization of Other Modules Modules other than main start with the keyword module Implementation section starts with the keyword implements Follow the model presented below module module name include include other modules KK ck ck ck kockck kckckckck ck ckck Interface globals Ck kk ck KKK KKK KKK ko kc ck kckckckck ck symbols declarations symbol constants declarations const structures declarations structure variables declarations dim Name Name2 as type absolute 0x123 external volatile register sfr procedures prototypes sub procedure sub procedure name dim byref const ParamName as type dim byref const ParamName2 ParamName3
425. uty dim duty as byte Changes PWM duty ratio Parameter duty takes values from 0 to 255 where 0 Description is 0 127 is 50 and 255 is 100 duty ratio Other specific values for duty ratio can be calculated as Percent 255 100 2 PWM module must to be initialised PWMY1 Init before using PWM Set Duty function For example lets set duty ratio to 75 PWM1 Set Duty 192 PWMA Start MCU must have CMO module to use this library PWM1 Init must be called before using this routine PWMA Stop Stops the PWM MCU must have CMO module to use this library PWM1 Init and PWM1 Start must be called before using this routine using this routine otherwise it will have no effect as the PWM module is not running 314 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Library Example The example changes PWM duty ratio on pin PB3 continually If LED is connected to you can observe the gradual change of emitted light program PWM Test dim current duty as byte current dutyl as byte main DDBO bit 0 Set PORTB pin 0 as input DDBI bit 0 Set PORTB pin 1 as input DDC bit 0 Set PORTC 0 as input bit 0 Set PORTC pin 1 as input current duty 127 initial value for current duty current dutyl 127 initial value for current duty DDBS bit 1 Set PORTB pin 3 as output pin for the PWM according to d
426. ve absolute deeded Ire edis 166 Directive Org uei earns og eae kee eee RR Ed 166 CHAPTER 6 Hardware AVR specific Libraries 168 Miscellaneous Libraries 168 Library Dependencies 169 ADC LIDIAly s oes ree gehn hrs ded e Rp c eek XC eons 170 XII MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Table of Contents ADG Read ce OE Ee RON ed Rte ce Ca ee o RR n 170 Library Example 21r edet ded bos 170 This example code 170 HW Connection 2 ea d e EA 171 CANSPI Library 172 External dependencies of CANSPI Library 173 Library Routlnes uot ded aap 173 CANSPISetOperationMode 174 CANSPIGetOperationMode 174 CANSPIllnitialize 175 CANSPISetBaudRate 177 CANSPISetMask 178 CANSPISetFilter 179 CANSPIRBead nete ond ets roe NER o CR Red 180 ERI RR RE E ERA EN 181 CANSPI Constants
427. viously assigned See Cf Fat Assign open file for appending Cf Fat Append Cf Fat Delete Deletes currently assigned file from CF card delete current file Cf Fat Delete CF card and CF library must be initialized for file operations See Cf Fat Init Requires File must be previously assigned See Cf Fat Assign 200 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Cf Fat Write sub procedure Cf Fat Write dim byref fdata as byte 512 dim Prototype data len as word Writes requested number of bytes to currently assigned file opened for writing Description Parameters fdata data to be written data len number of bytes to be written CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign File must be open for writing See Cf Fat Rewrite or Cf Fat Append dim file contents as 42 of byte Cf Fat Write file contents 42 write data to the assigned file sub procedure Cf Fat Set File Date dim year as word dim month as byte dim day as byte dim hours as byte dim mins as byte dim seconds as byte Sets the date time stamp Any subsequent file writing operation will write this stamp to currently assigned file s time date attributs Parameters Description Year attribute Valid values 1980 2107 month month attribut
428. w Unit Open Ctrl O Recent Files Ctrl s L Close Ctrl F4 Print Ctrl P Exit Alt X File Description New Unit Ctrl N Open a new editor window e Open Ctr O Open source file for editing or image file for viewing ecent Files Reopen recently used file H save Ctrlt S Save changes for active editor Save the active source file with the different name or change the file type 11 Close Alt F4 Close active source file xm Print CtrieP Print Preview Exit IDE Related topics Keyboard shortcuts File Toolbar Managing Source Files 14 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR EDIT MENU OPTIONS CHAPTER 2 Environment undo Ctri z Redo Shift Ctr Z do Cut Ctrl C 3 Paste Ctrl V XxX Delete Select All Ctri A Find Ctrl F Jd Find Next F3 92 Find Previous Shift F3 Replace Ctr R Find In Alt F3 1 Goto Line Ctrl G Advanced File Description undo Ctrl Z Undo last change Redo Shift Ctrl zZ Redo last change Cut Ctri Cut selected text to clipboard E3 Copy Ctrl C Copy selected text to clipboard B Paste Ctril Paste text from clipboard Delete Delete selected text Select All Ctr A Select all text in
429. ware 2 must be configured before using this function See Soft I2C Init routine Issue START signal soft I2C Start Soft I2C Read Prototype sub function Soft I2C Read dim ack as word as byte Returns One byte from the Slave Reads one byte from the slave Description Parameters ack acknowledge signal parameter If the ack 0 not acknowledge signal will be sent after reading otherwise the acknowledge signal will be sent Soft 12 must be configured before using this function See Soft 2 Init routine Also START signal needs to be issued in order to use this function See Soft I2C Start routine dim take as word Read data and send the not acknowledge signal take Soft I2C Read 0 340 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries Soft I2C Write Prototype sub function Soft I2C Write dim Data as byte as byte 0 if there were no errors 1 if write collision was detected on the 2 bus Sends data byte via the I C bus Description Parameters Data data to be sent Soft 2 must be configured before using this function See Soft 2 Init routine Also START signal needs to be issued in order to use this function See Soft I2C Start routine dim data error as byte error Soft I2C Write data error Soft IZU Write 0xA3 Soft I2C Stop Issues STOP signal Soft 2 must be configured before u
430. x except that the signs of both arguments are used to determine the quadrant of the result and x is permitted to be zero The return value is in radians between and n inclusive Description ceil pe sub function ceil dim x as real as real The function returns value of parameter rounded up to the next whole number ae sub function cos dim arg as real as real The function returns the cosine of arg in radians The return value is from 1 to 1 cosh Prototype sub function cosh dim x as real as real The function returns the hyperbolic cosine of x defined mathematically as D ipti 1 egeripuen 2 If the value of x is too large if overflow occurs the function fails eval_poly sub function eval poly dim x as real dim byref d as array 10 real dim n as integer as real Prototype Function Calculates polynom for number x with coefficients stored in degree n Description 486 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Libraries exp Prototype sub function sub function exp dim x as real as real as real as real Peene NN function returns the value of the base of natural logarithms raised to Description the power i e fabs Prototype sub function fabs dim d as real as real The function returns the absolute i e positive value of a floor Prot
431. x00 Clear Glcd while TRUE Glcd Image G8truck Draw image Delay2S delay2S Fill 0x00 Clear Glcd Glcd Box 62 40 124 63 1 Draw box Gled Rectangle 5 5 84 35 1 Draw rectangle Gled tane 0 0 127 63 1 Draw line Delay2S counter 5 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 231 CHAPTER 6 Libraries mikroBasic PRO for AVR while counter lt 59 Draw horizontal and vertical lines Delay ms 250 Gled V Line 2 54 counter 1 Gled H Line 2 120 counter 1 Counter counter 5 wend Delay2S Glcd Fill 0x00 Clear Glcd Gled Set Font Character8xT7 8 73 32 Choose font Character8x7 Glod Write Text mrkroE 1 7 2 Write string for counter 1 to 10 Draw circles Gled Circle 63 92 3 count r 1 next counter Delay28S Gleda Box 12 20 70 57 2 Draw box Delay2S Gled Fill OxFF Paid Gied Gled Set Font Charactersx7 8 7 32 Change font someText 8x7 Font Gled Write Text someText 5 0 2 Write string delay2S Gled Set Font GSystem3x6 3 5 32 Change font someText 3X5 CAPITALS ONLY Gled Write Text someText 60 2 2 Write string delay2S Gled Set Font fontsx7 5 7 32 Change font someText 5x7 Font Gled Write Text someText 5 4 2 Write string delay2S Glod Set Font ronteystemsx v2 8 1 32 Change font someText 5x7 Font v2 Gled Write Text someText 5 6
432. xecutable logic with the integrated Software Simulator Get detailed reports and graphs RAM and ROM map code statistics assembly listing calling tree and more mikroBasic PRO for AVR provides plenty of examples to expand develop and use as building bricks in your projects Copy them entirely if you deem fit that s why we included them with the compiler 2 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroBasic PRO for AVR Introduction Where to Start In case that you re a beginner in programming AVR microcontrollers read carefully the AVR Specifics chapter It might give you some useful pointers on AVR constraints code portability and good programming practices If you are experienced in Basic programming you will probably want to consult mikroBasic PRO for AVR Specifics first For language issues you can always refer to the comprehensive Language Reference A complete list of included libraries is available at mikroBasic PRO for AVR Libraries If you not very experienced in Basic programming don t panic mikroBasic PRO for AVR provides plenty of examples making it easy for you to go quickly We suggest that you first consult Projects and Source Files and then start browsing the examples that you re the most interested in MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 3 CHAPTER 1 Introduction mikroBasic PRO for AVR MIKROELEKTRONIKA ASSOCIAT
433. xpression is treated as the function result In standard Basic a function name is automatically created local variable that be used for returning a value of a function mikroBasic PRO for AVR also allows you to use the automatically created local variable result to assign the return value of a function if you find function name to be too ponderous If the return value of a func tion is not defined the compiler will report an error Function calls are considered to be primary expressions and can be used in situa tions where expression is expected A function call can also be a self contained statement and in that case the return value is discarded MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 131 CHAPTER 5 Language Reference mikroBasic PRO for AVR Example Here s a simple function which calculates x based on input parameters x and n n gt 0 sub function power dim x n as byte as longint dim i as byte result 1 if n 0 then for 1 result result x next i end 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 procedure name represents a procedure s name and can be any valid identifier Within parentheses parameter list is aformal parameter list similar to variable declaration In mikroBasic PRO for AVR para
434. xt The following routine is for the internal use by compiler only UARTx TX Idle Note AVR MCUS require you to specify the module you want to use To select the desired UART simply change the letter x in the prototype for a number from 1 to 4 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Example vART2 1 lt initializes UART 2 module Note Some of the AVR MCUs do not support UARTx Init Advanced routine Please refer to the appropriate datasheet MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 469 CHAPTER 6 Libraries UARTXx Init Prototype Description mikroBasic PRO for AVR sub procedure UARTx Init dim baud rate as longint Nothing Configures and initializes the UART module The internal UART module module is set to receiver enabled transmitter enabled frame size 8 bits 1 STOP bit parity mode disabled asynchronous operation Parameters baud rate requested baud rate Refer to the device data sheet for baud rates allowed for specific Fosc You ll need AVR MCU with hardware UART UARTXx Init needs to be called before using other functions from UART Library This will initialize hardware UART1 module and establish the communication at 2400 bps UART1 Init 2400 470 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroBasic PRO for AVR Lib
435. xt and graphic data shown on the display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Toshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C Write Text Glcd LIBRARY DEMO W T6963C ROM MODE _EXOR 427 CHAPTER 6 Libraries mikroBasic PRO for AVR SPI T6963C Line sub procedure SPI T6963C Line dim x0 as integer dim 0 as inte ger dim x1 as integer dim yl as integer dim pcolor as byte Nothing Draws a line from x0 yO to x1 y1 Parameters x0 X coordinate of the line start y0 y coordinate of the line end x1 X coordinate of the line start yl y coordinate of the line end pcolor color parameter Valid values SPI T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine ENS T6963C Line 0 0 239 T6963C WHITE SPI T6963C Rectangle Description sub procedure SPI T6963C Rectangle dim x0 as integer dim 0 as integer dim x1 as integer dim yl as integer dim pcolor as byte Draws a rectangle on Glcd Prototype Parameters x0 X coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right recta
436. y 322 HW Connection 22 42 5 ZEE AEN TRY 324 PWM demonstrati 324 RABI LIDI eeri aia phe enm Pod deed Pt dor d 325 External dependencies of RS 485 326 Library Routines 326 RS485Master Init 327 RS485Master Receive 328 RS485Master Send 329 RS485S lave uit i wer Ra d 330 RS485Slave Receive 331 RS485Slave Send 332 Library Examiple eae eee ene es 332 HW Connection 336 Message format and CRC calculations 337 Software PC 2 4 338 External dependencies of Soft I2C 338 Library Routines 339 Soft 2C IMME xor RR 339 XVIII MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroBasic PRO for AVR Table of Contents Soft 2C Slant cess n ee EROR a TA 340 Soft I2C Read luda de aree Dac 340 Soft I2C Writes
437. y customize the layout of mikroBasic PRO for AVR to suit your needs best Spell checker underlines identifiers which are unknown to the project In this way it helps the programmer to spot potential problems early much before the project is compiled Spell checker can be disabled by choosing the option in the Preferences dialog F12 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 31 CHAPTER 2 Environment mikroBasic PRO for AVR CUSTOMIZING IDE LAYOUT Docking Windows You can increase the viewing and editing space for code depending on how you arrange the windows in the IDE Step 1 Click the window you want to dock to give it focus 4 B LedBlinking mbpav 7j Sources i L LedBlinking mbas 125 Project level defines 17 Image Files 7j Output Files 73 Other Files Step 2 Drag the tool window from its current location A guide diamond appears The four arrows of the diamond point towards the four edges of the IDE Other Files 32 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroBasic PRO for AVR Environment Step 3 Move the pointer over the corresponding portion of the guide diamond An outline of the window appears in the designated area gt Step 4 To dock the window in the position indicated release the mouse button Tip To move a dockable window without snapping it into place press
438. you may overlap two variables by accident For example dim 1 as word absolute 0x42 Variable i will occupy 1 word at address 0x42 dim jj as longint absolute 0x40 Variable will occupy 2 words at 0x40 and 0x42 thus changing i changes jj at the same time and vice versa Note You must specify an even address when using the directive absolute Directive org The directive org specifies the starting address of a routine in ROM It is appended to the declaration of routine For example sub procedure proc dim par as word org 0x200 Procedure will start at the address 0x200 end sub Note You must specify an even address when using the directive 166 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER mikroBasic PRO for AVR Libraries mikroBasic PRO for AVR provides a set of libraries which simplify the initialization and use of AVR compliant MCUs and their modules Use Library manager to include mikroBasic PRO for AVR Libraries in you project 167 CHAPTER 6 Libraries mikroBasic PRO for AVR HARDWARE AVR SPECIFIC LIBRARIES ADC Library CANSPI Library Compact Flash Library EEPROM Library Flash Memory Library Graphic Lcd Library Keypad Library Lcd Library Manchester Code Library Multi Media Card library OneWire Library Port Expander Library PS 2 Library PWM Library PWM 16 bit Library RS 485 Library Software I2C Library
439. ypes in mikroBasic PRO for AVR we 6 80564774407 Pp E ER pet o You can assign signed to unsigned or vice versa only using the explicit conversion Refer to Types Conversions for more information MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 137 CHAPTER 5 Language Reference mikroBasic PRO for AVR ARRAYS An array represents an indexed collection of elements of the same type called the base type Since each element has a unique index arrays unlike sets can mean ingfully contain the same value more than once Array Declaration Array types are denoted by constructions in the following form typel array length Each of elements of an array is numbered from o through array length 1 Every element of an array is of type and can be accessed by specifying array name fol lowed by element s index within brackets Here are a few examples of array declaration dim weekdays as 7 dim samples 50 main Now we can access elements of array variables for example samples 0 1 if samples 37 0 then Y Constant Arrays Constant array is initialized by assigning it a comma delimited sequence of values within parentheses For example Declare a constant array which holds number of days in each month const MONTHS as bytel 12 31 25 231 30 21 390 31 91 30 31 230 31 Note that indexing is zero based in the previous example number of days in Ja

Download Pdf Manuals

image

Related Search

Related Contents

FUNKTIONSGENERATOR FG 8210 FUNCTION GENERATOR FG  グリル  Garmin Approach G7 Owner's Manual  HDS Serie - Lowrance  troubleshooting résolution de problèmes fehlerbeseitigung  

Copyright © All rights reserved.
Failed to retrieve file