Home

mikroC for 8051 User Manual

image

Contents

1. 8 9 A FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF B FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF D FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF E FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF CHAPTER 2 mikroC for 8051 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 Decoderor by clicking the Seven Segment Icon from Tools toolbar Seven Segment Editor Common cathode Common anode Decode in 2 decimal value AAA MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 63 CHAPTER 2 Environment mikroC for 8051 UDP Terminal The mikroC for 8051 includes the UDP Terminal You
2. jl 000000000000 com 4F5A 5B6266 84775F 68509 Select your r dis stributor From the lis st 4F5A 5B6266 84775F 68509 Distributor Select your distributor from the list Copy to Ea Gpboard MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 9 CHAPTER 1 Introduction mikroC for 8051 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 mikroC for 8051 at the time of activation Notes The license key 15 valid until you format your hard disk In case you need to format the hard disk you should request a new activation key Please keep the activation program in a safe place Every time you upgrade the compiler you should start this program again in order to reactivate the license MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMB
3. 359 MCCC 359 Obl OCA TD 360 OGICA LING APP 360 V LING auc a bees ing 361 xx SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 Table of Contents opi Gled 361 5 5 _ _ 362 Obl BOX oer esse nee ee ease 363 Obl Gld CWS 22 0 aa he Be eee eRe 363 Spi Gicd Sel ETT 364 Spi _Glcd_Write_Char 365 Gled Write 366 Gled Image 367 Library 367 HW Connection s sone agire aed ndikata bireti Depia 369 SPI LGD LIDAN mto 370 External dependencies of SPI LCD 370 Library ROUES aes bad 370 371 ECO OUL genase pee 371 Spi Led QUL RUP 372 SDI Led SON 5 sens ete ease 372 Led bab MEER ER
4. OSC1 RXOB 1 Vss RX1B 710 MCP2510 _ 54 85681 OSCILLATOR Shielded I twisted pair 6 1 Example of interfacing CAN transceiver MCP2510 with MCU via SPI interface MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 239 CHAPTER 6 Libraries mikroC for 8051 EEPROM LIBRARY EEPROM data memory 15 available with a number of 8051 family The mikroC for 8051 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 con strains Library Routines Eeprom Read Eeprom Write Eeprom Write Block Eeprom Read Prototype unsigned short Eeprom Read unsigned int address Byte from the specified address Description Reads data from specified address Parameters address address of the EEPROM memory location to be read Example unsigned int eeAddr unsigned short temp temp BeadteseAgdr 240 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Eeprom_Write Prototype unsigned short Eeprom Write unsigned int address unsigned short wrdata Returns 0 writing was successful 1 if error occured Description Writes wrdata to specified address Parameters address address of the EEPROM memory location to be
5. 37 Docking Windows 37 Auto 39 Saving Layout von ea ons oo ewes hes oe oot kde depos 39 Once you have a 39 Advanced Code 41 Advanced Editor Features 41 saei e 43 C OUS ASSISA ese tears gas TS VERIS UOS TP PESE SS 43 Parameter Assistant 44 Code Templates Auto Complete 44 BOOKMATKS 5 RIOT C t DL DOTT TIT 45 Goto Line 45 Corect 225 454 e e 600 Edun E on 45 Code EXBIOIGI fasts gees ees td epee dees obs ene WAS 46 T acdec oe thee dd deed ewer 47 Project Ma nage 2405475424 2 92 0 3 4 22 83 908 2 9 39458 28 3 diac WE dr eae 48 Project Settings Window 49 Library Manag cans sean te dane nas peda ee doh oo 50 usse Lew 52 Memory Usage 52 RAM MEMON Pw 52 AUC seb A
6. 243 External dependencies of Graphic LCD Library 243 Library ROUUNES 24444 57 90 32 93 79 ees ro sd a t 45 Sa ee 244 COMI amp RA eh tne eae 245 SEU Ae ase Ose Cho e 246 cease eae eo 246 led Read 247 Gled Sel Page 247 _ _ 248 ICG Fill METER 248 ICO LING rr 249 ICE tooo Seaweed Good Lew eee ede 22 dened 249 CN SLING wise ma bead oe eae eae 250 Gica A eed ot Heese ee oe ee ee 250 Glod sss si rerit S 251 Gicd BOX 252 222225552424 0252 44 yee 252 Gled Set 2204 yr henge a xu dy ERES ERE MEME 253 Gled Write 254 Glcd_Write_Text 255 IGG IMAG 6 sa ode eas Boe wee TIPP 255 Library 2
7. 8 90 Stopwatch Window 92 RAM Bus se a cae a saagaa oo as oe ee eae 93 Software Simulator Options 94 Creating New Library 95 Multiple Library Versions 95 CHAPTER 3 ANSI Standard Issues 98 Divergence from the ANSI C Standard 98 C Language 98 Accessing Individual Bits 99 Accessing Individual Bits Of Variables 99 Predefined Globals and Constants 99 SUI DO sais oes bee ewes 100 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD vii Table of Contents mikroC for 8051 msc a a a ee ere ee ere ee es 100 jocis oce 101 Function Calls from Interrupt 101 Interrupt Priority Level 101 Linker Directives 102 Directive absolute 102 Directive Org 102 Built in 103 Indirect Func
8. 197 Compound Assignment Operators 197 Assignment Rules 198 Sizeof Operator 198 Sizeof Applied to Expression 199 Sizeof Applied to 199 iere mer ae a a E E 200 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD xili Table of Contents mikroC for 8051 Comma Expressions 200 4 39 009 9299 v 205 8 0 8 545 Bee 201 Labeled Statements 202 Expression Statements 202 Selection Statements 203 f Statement rm 203 Nested If statements 203 Note 203 Switch Statement 204 Nested switch 205 Iteration Statements Loops 205 While 205 DO Statement T TITRE TO TOT I OS ae wee ewe 206 For Statement CT 206 Jump StatemMeNiS ax excea m eiaa ind
9. 268 Library 268 HW COMMCCIION 6 52 uno e 05 oes om lt lt lt ow hE epee ences 270 One Wire 271 External dependencies of OneWire Library 271 Library ROUES outa wena bs ne Dodo aac enaka aA 2 2 OW INGSEE reacia a9 d 9 50954 Pees ede Ding ese ese 272 OW Read 272 Ow Write 273 I 273 HW Connection 276 External dependencies of Manchester Code Library 277 Manchester Code Library 277 Library 3 293 9 9 22859 eet eke 278 Man Receive 278 Man Send lil Hoda 279 _ 279 Man ale oe 280 EXAMPIC terse d a dr Variedad cardo weed c 280 Mati Seld 280 Connection Example 283 Port Expander Library 284 External dependenci
10. 188 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference ARITHMETIC OPERATORS Arithmetic operators are used to perform mathematical computations They have numerical operands and return numerical results The type char technically repre sents small integers so the char variables can be used as operands in arithmetic operations All arithmetic operators associate from left to right Arithmetic Operators Overview Binary Operators ERN MEM NN mulplication Lf modulus operator returns the remainder of inte ger division cannot be used with floating points Unary Operators unary minus changes the sign of the operand increment adds one to the value of the operand Postincrement adds one to the value of the operand after it evaluates while preincrement EE adds one before it evaluates decrement subtracts one trom the value of the operand Postdecrement subtracts one from the value of the operand after it evaluates while predecrement subtracts one before it evaluates unary plus does not affect the operand 14 Note Operator is context sensitive and can also represent the pointer reference operator Binary Arithmetic Operators Division of two integers returns an integer while remainder is simply truncated MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 189 CHAPTER 5
11. 76 vi MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 Table of Contents Customizing Projects 80 Edk POCO Gea beers 80 Managing Project Group 80 Add Remove Files from 81 PICS oe aS Se TRITT 82 Managing Source Files 82 Creating new source file 82 Opening an existing 83 Printing open 83 SED d o4 ow one ows Faces 83 Saving file under a different name 83 ollm 84 Clean Project Folder 84 Assembly View 85 COMDIGHON EE E yee 85 Output Files eet esis ten ares ods 85 zou 86 Compiler Error 86 Compiler Warning lt 89 Software Simulator Overview 90 Watch WINGOW ses coise een dee
12. Imeqe mc T6963C Sprite Prototype void 6963 Sprite unsigned char px unsigned char py const code char pic unsigned char sx unsigned char sy Description Fills graphic rectangle area px to py sy with cus tom size picture Parameters px X coordinate of the upper left picture corner Valid values multiples of the font width coordinate of the upper left picture corner pict picture to be displayed sx picture width Valid values multiples of the font width sy picture height Note If px and sx parameters are not multiples of the font width they will be scaled to the nearest lower number that is a multiple of the font width Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Example T6963C Sprite 76 4 einstein 88 119 draw a sprite 418 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries T6963C Set Cursor Prototype void T6963C Set Cursor unsigned char x unsigned char y Description Sets cursor to row x and column y Parameters x cursor position row number y cursor position column number Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Lursori cposx cposy T6963C ClearBit Description Clears control port bit s Parameters b bit mask The function will clear bit
13. 296 FOUUNCS 992 13 999 9 3 43 basen Vd es Idi d ddp 296 Ps2_Config 296 Koy 2252 ra goede ED 296 Ps2 CONIO Soe He ee eee ee eens 296 Ps2 Key Read 297 special Function Keys 298 Library Example aic dc aree 2 2 9x ea dea unk eee deemed ES RE 299 HW Connection 300 UID TCR 301 External dependencies of RS 485 301 Library ROUUNES RTT 302 5485 _ 302 RS485master Receive 303 R5495master Send 303 R54955slave Init EX nx See 304 RS485slave Receive 304 RS485slave 305 Library Example rm edet 305 HW Connection P 309 Message format CRC calculations 310 Sofware FO LIDIA hee ii mie aga hea Go AA E ane 311 External dependecies of Soft I2C Library 311 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED W
14. 64 Graphic LCD Bitmap 65 LCD Custom Character 66 5 3 2 66 Code Cdl 52522255242 gone eon ee 66 TOO Mau 66 Output settings 68 Regular Expressions 69 245 aecua wes 9 5 E 69 Simple matches 69 Escape sequences 69 Character classes 70 Metacharacters 70 Metacharacters Line separators 71 Metacharacters Predefined classes 71 Metacharacters Word boundaries 72 Metacharacters Iterators 72 Metacharacters Alternatives 73 Metacharacters Subexpressions 74 Metacharacters Backreferences 74 mikroC for 8051 Command Line Options 75 miu a eae he oe eas 76 NEW FOGOL sage oe wim 76 New Project Wizard Steps
15. Changes selected text case to uppercase Uppercase Changes selected text case to titlercase Ad Titlecase 16 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Find Text Dialog box for searching the document for the specified text The search 15 formed the direction specified If the string 15 not found a message 15 displayed Find Text Search for E A E Replace Text Dialog box for searching for a text string in file and replacing it with another text string 4 Replace Text Search for el JHHTPEHHH HEISE PI MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 17 CHAPTER 2 Environment mikroC for 8051 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 1s 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 Grep search Text to find mikroElektronika Options Where Case sensitive Current file cance Go To Line Dialog box that allows the user to specify the line number at which the cursor should be positioned Go To Line Go To Line Nuber 1 18 MIKROELEKTRONIK
16. Increment index variable character 81 index Take next char from string Man 0 0 44 Send end byte Delay ms 1000 282 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Connection Example vcc o VCC Receiver RF module Antenna vcc Gc8S681V OSCILLATOR Transmitter RF module Antenna G68S681V OSCILLATOR 6 6 Simple Receiver connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 283 CHAPTER 6 Libraries mikroC for 8051 PORT EXPANDER LIBRARY The mikroC for 8051 provides a library for communication with the Microchip s Port Expander MCP23S17 via SPI interface Connections of the 8051 compliant MCU and 23517 15 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 Library does not use Port Expander interrupts External dependencies of Port Expander Library The following vari ables must be defined in all projects using Description Example Port Expander Library extern sbit Chip Select line soit SPExpanderCS at P1 B1 SPExpanderCs extern sbit bit SPE derRST at P1 B0 Reset line sbi xpander Library Routines Expander_Init Expander Read Byte Expander Write Byte Expander R
17. Uart Write byte read If error was not detected return byte read 324 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 CHAPTER 6 Libraries SOUND LIBRARY The mikroC for 8051 provides a Sound Library to supply users with routines neces sary for sound signalization in their applications Sound generation needs addition al hardware such as piezo speaker example of piezo speaker interface 1s 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 Example extern sbit Sound output sbit sound Play Pin at Sound Play Pin i Library Routines Sound Init Sound Play MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 325 CHAPTER 6 Libraries mikroC for 8051 Sound_Init Configures the appropriate MCU pin for sound generation Requires Sound Play Pin variable must be defined before using this function Example Initialize the pin 0 3 for playing sound Sound Play Pin at pound nit 7 Sound_Play Prototype void Sound Play unsigned freq in hz unsigned duration ms Description Generates the square wave signal on the appropriate pin Parameters freq in hz signal frequency in Hertz Hz duration ms signal duration in miliseconds ms Require
18. f SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD display only graphic panel display only text panel display text and graphic panels 429 CHAPTER 6 Libraries mikroC for 8051 if IZ S pressed change Cursor id else if P2 4 cursf 3 if curs 3b curs 0 switch curs case 0 no GOHFPFBOF TOJO break case 1 blinking cursor cursor l j TOJO cursor j break 3 case 2 77 non DlInking cursor TOSDIL ODESOELU 799520 Cursor 3 break Delay me s0U 3 Move cursor even if not visible pPposxi j ALLicposx EXICOIS cposx 0 j if cposy T6963C grHeight T6963C CHARACTER HEIGHT cposy 0 TOSDOL ceosy 2 Delay ms 100 430 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries HW Connection 1 Po2L _ cb C 4 xl ae JEA CO O P0 7 154 Reset oo Toshiba T6963C Graphic LCD 240x128 32 IINHSS 8T UU UUUUUUUUUUUUTU gt Contrast Adjustment 6 17 T6963C GLCD HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 431 CHAPTER 6 Libraries mikroC for 8051
19. 440 440 ci Pr 440 A ee 440 440 ene esas Ae ee ew 441 s 441 441 XD etc ae auis Ur Be enw ied qb wl ow a Sea 441 E 441 MOO 4 aes oan beeen eee 441 MOD 4X 442 eo Sane ce arses 442 OG 22552555505 ee eee ee mE Ae Pree wee werd 442 52252242502 epee es bese ecw oes cet AS 442 xxiv MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 Table of Contents lue oo ot ave 442 DOW een eee eae 442 SI gaa gee es ee eee ee a a ee 443 SI rea bees A ae Pe 443 cop 5425052 oe eee eee ee E E 0 443 443 CI gro seme ice oe wR Be ae Re 443 ANSI C Stdlib 444 lt 4 aes de ote ea ee ae ee OM
20. J Output 42 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Code Assistant If you type the first few letters of a word and then press Ctrl Space all valid iden tifiers matching the letters you have typed will be prompted 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 op valable hr unsigned char SP valable sfr unsigned char SPDR valable sh unsigned char SPSA valable sfr unsigned char SPCR 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 1s 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 maint PO 0 Pa D Led Init i LCD Outti 1 txt O LCD Outfe 1 txt 1 delay ms 1000 Led Cmd 1 LCD Outti 1 txt i i LCD Out iz 23 txt z delay ms 500 void main l If you place a mouse cursor over the tooltip box the collapsed text will be shown in a tooltip style box MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 43 CHAPTER 2 Envi
21. CANSPI module must be in a mode in which receiving 15 possible See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CAN SPI Extra Board or similar hardware See connection example at the bottom of this page Example check the CANSPI module for received messages If any was received do something char mog rovod rx flags data len char datal 8 long msg id CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode CANSPI module must be in mode in which receive is possible fx 0j clear message flags Ir rovag i0 data Gata ien rx flags 1 CANSPIWrite Prototype char CANSPIWrite long id char wr data char data len char CAN TX MSG FLAGS Returns 0 if all Transmit Buffers are busy OxFF 1f at least one Transmit Buffer is available Description If at least one empty Transmit Buffer is found the function sends message in the queue for transmission Parameters id CAN message identifier Valid values 11 or 29 bit values depending on message type standard or extended 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 231 CHAPTER 6 Libraries Requires E
22. be useful to dis play text in negative mode 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 Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Spi T6963C Write Char A 22 23 AND 390 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi T6963C Write Text Prototype void Spi T6963C Write Text unsigned char str unsigned char x unsigned char y unsigned char mode Description Writes text in the current text panel of GLCD at coordinates x y Parameters str text to be written text position on x axis y text position on y axis mode mode parameter Valid values Spi T6963C ROM MODE OR Spi T6963C ROM MODE Spi T6963C ROM MODE AND and Spi T6963C ROM MODE TEXT Mode parameter explanation OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are com bined via the logical exclusive OR This can be useful to dis play text i
23. 1 CLEAR 77 Clear display LED DULL Li 77 Write text Airs row LCD Out 2 4 txt2 Write text in second row Delay ms 500 Moving text for i 0 1 lt 4 i Move text to the right 4 times Lcd Cmd LCD SHIFT RIGHT Move Delay while 1 Endless loop for i 0 i 7 i 4 Move text to the left 7 times Lcd Cmd LCD SHIFT LEFT Move Delay for i 147 144 4 Move text to the right 7 times Lea Cma LcD SHIFT RIGHT Move Delay MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 269 CHAPTER 6 Libraries mikroC for 8051 HW connection 85968 1 OSCILLATOR 3333333333331 LCD 2X16 6 4 LCD HW connection 270 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries ONEWIRE LIBRARY The OneWire library provides routines for communication via the Dallas OneWire protocol e g with DS18x20 digital thermometer OneWire is a Master Slave 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 distanc
24. T t 507 const char msg2 Test For more information on string literals refer to String Constants Arrays in Expressions When the name of an array comes up in expression evaluation except with opera tors and sizeof it is implicitly converted to the pointer pointing to array s first element See Arrays and Pointers for more information Multi dimensional Arrays An array 1s one dimensional if it is of scalar type One dimensional arrays are some times referred to as vectors Multidimensional arrays are constructed by declaring arrays of array type These arrays are stored in memory in such way that the right most subscript changes fastest arrays are stored in rows Here is a sample of 2 dimensional array float m 50 20 2 dimensional array of size 50x20 A variable m is an array of 50 elements which in turn are arrays of 20 floats each Thus we have a matrix of 50x20 elements the first element is m 0 0 the last one is m 49 19 The first element of the 5th row would be m 41 01 If you don t initialize the array in the declaration you can omit the first dimension of multi dimensional array In that case array 1s located elsewhere e g in another file This is commonly used technique when passing arrays as function parameters MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 155 CHAPTER 5 Language Reference mikroC for 8051 int 3
25. oe eee oe 5 eee 458 DOC BOO 5 4 de tees 4 459 BCOZDCCIG d eee dd 459 TD x49 amp vas 97 E 460 sedi A r m 461 mis es 461 SDM oe 24 aes ee ee EET 461 ze 44 2 are aged wie are ore Adal eee cue eee Se ewe 465 SOMME cece oy S ESO REP 465 Library 465 Tim LIDrary se as ae hw oh a ete ede ae 467 Library Routines 467 Time Gale lOEpOCn 467 Time epochToDate 468 rm 469 Trigonometry Library 470 ROUUNES 2 240454 sscan iaaa iea oo ee 470 xxvi MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 Table of Contents MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD xxvii Table of Contents mikroC for 8051 xxvii MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER Introduction to mikroC 8051 The mikroC 8051 is a po
26. tsl mo 5 tsl yy 2006 What is the epoch of the date ts epoch Time GateToEpocbhistsl j What date is epoch 1234567890 we epoch 1234567890 Tite eoochTobare epoch 652 7 How much seconds between this two dates d Time 8 50 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 469 Table of Contents mikroC for 8051 TRIGONOMETRY LIBRARY The mikroC for 8051 implements fundamental trigonometry functions These func tions are implemented as look up tables Trigonometry functions are implemented in integer format in order to save memory Library Routines sinE3 cosE3 sinE3 The function returns the sine of input parameter Description The function calculates sine multiplied by 1000 and rounded to the nearest integer result Bound sin tangle deg 1000 Parameters angle deg input angle in degrees Note Return value range 1000 1000 Example int res res sinE3 45 result is 707 470 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries cosE3 Prototype int cosE3 unsigned angle deg The function returns the cosine of input parameter Description The function calculates cosine multiplied by 1000 and rounded to the nearest integer result roundicoslangle deg 1000 Parameters angle deg input angle in
27. 444 zo axon det Gk eee dae on en ew 444 ALON ied he ae awh a ed ee ee ee 445 zc eae oe eo 445 cj 445 op Aa tans pace be ee ee 445 ip m O 446 le tes nd ww gh cede arate ak ge ae re 446 ADS aed ee ee eee oe eee 446 WOK se ee ee ee Se ee eee 446 opens A er cg Se hob oe tes a at ns aad oh eae wtp a oe eg dae cea 446 eh es ce 447 cCrc 447 dM T 447 Div Structures 447 ANSI C Sting LIBA ed ceni oaa rd i Ys 448 FUNCIONS T 448 v e546 1550 25 Le aoe es oe eee oe oes ad oes 448 ins D 449 ge PDT 6 449 MeMMOVe 449 memset 449 cipe e 449 dae Le ew wd oe
28. MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 323 CHAPTER 6 Libraries mikroC for 8051 Soft_Uart_Write Prototype void Soft Uart Write char udata Nothing Description This routine sends one byte via the Software UART bus Parameters udata data to be sent Requires Software UART must be initialized before using this function See the Soft Uart Init routine Be aware that during transmission software UART is incapable of receiving data data transfer protocol must be set in such a way to prevent loss of information Example char some byte Ox0A Write a byte via Soft Uart POIL Uart Wrice some Dye Library Example This example demonstrates simple data d via software UART If MCU is connected to the PC you can test the example from the mikroC for 8051 USART Terminal Tool Soft UART connections sbit Soft Uart RX at P3 B0 sbit Soft Uart TX at End Soft UART connections 1 error Dyte read Auxiliary variables void main Soft Uart Init 4800 0 Initialize Soft UART at 4800 bps for i z i gt i Send bytes from downto colt Uart Write Delay ms 100 while 1 Endless loop byte read Sort Uart Bead amp error Read byte then test error flag if error If error was detected PD ORAA signal it on PORTO else
29. Prototype unsigned short tolower char character Description If the character is an uppercase letter A Z function returns a lowercase letter Otherwise function returns an unchanged input parameter 438 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries ANSI C MATH LIBRARY The mikroC for 8051 provides a set of standard ANSI C library functions for float ing point math handling Note Not all of the standard functions have been included Note The functions have been mostly implemented according to the ANSI C stan dard but certain functions have been modified in order to facilitate 8051 program ming Be sure to skim through the description before using standard C functions Library Functions acos asin atan atan2 ceil cosh eval poly exp fabs floor frexp ldexp log 10210 modf pow sin sinh sqrt tan tanh MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 439 CHAPTER 6 Libraries mikroC for 8051 5 Prototype double acos double x inclusive Description Function returns the arc cosine of parameter x that is the value whose cosine is x The input parameter x must be between 1 and inclusive The return value is in radians between 0 and asin Prototype double asin double x Description Function returns the arc sine o
30. Spl initialize SPI module LANSPIIDlEI1alise l 3 2 9 1 L m Int Flags initialize external CANSPI module CANSPISetBaudRate Prototype void CANSPISetBaudRate char SJW char BRP char PHSEG1 char PHSEG2 char PROPSEG char CAN CONFIG FLAGS Description Sets the CANSPI module baud rate Due to complexity of the CAN protocol you can not simply force a bps value Instead use this function when the CANSPI module is in Config mode SAM SEG2PHTS and WAKFIL bits are set according to CON FIG FLAGS value Refer to datasheet for details Parameters Sow as defined in CAN controller s datasheet BRP as defined in CAN controller s datasheet 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 1s formed from predefined constants see CANSPI constants MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 227 CHAPTER 6 Libraries mikroC for 8051 Requires CANSPI module must be in Config mode otherwise the function will be ignored See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CAN SPI Extra Board or similar hardware See connection example at the bottom of this page Example set required baud rate and sampling rules char can conrig Tl ags CANSPISetOperati
31. The mikroC for 8051 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 External dependencies are the same as Port Expander Library external dependen cies Library Routines Lcd Config Spi Led Out Spi Led Out Spi Lcd Chr Spi Led Chr Spi Led 370 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi Lcd Config Prototype void Spi Lcd Config char DeviceAddress Description Initializes the LCD module via SPI interface Parameters DeviceAddress spi expander hardware address see schematic at the bottom of this page Requires SPExpanderCs and SPExpanderRsT variables must be defined before using this function The SPI module needs to be initialized See Spi_Init and Spi Init Advanced routines Example port expander pinout definition sbit SPExpanderRST at P1 B0 sbi
32. ese 0 DENEN DENEN GNE SN eine aie Apap _ INN NENNEN I NN y Sng oF up o3 otal diis srng oF hex digs 0 Sng oF hex digs 0 Disambiguation Some ambiguous situations might arise when using escape sequences Here is an example nod pt 2031 0 Intseo 4 This is intended to be interpreted as x09 and 1 0 Intro However the mikroC for 8051 compiles it as the hexadecimal number 091 and literal string 0 Intro To avoid such problems we could rewrite the code in the following way Led Out Cot x09 1 0 Inbro For more information on the previous line refer to String Constants Ambiguities might also arise if an octal escape sequence is followed by a nonoctal digit For example the following constant 118 would be interpreted as a two character constant made up of the characters 11 and 8 because 8 is not a legal octal digit MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 131 CHAPTER 5 Language Reference mikroC for 8051 STRING CONSTANTS String constants also known as string literals are a special type of constants which store fixed sequences of characters A string literal is a sequence of any number of characters surrounded by double quotes string The null string or empty string is written like A literal string is stored internal ly as a given sequence of characters plus a final
33. 4 22 3 27 3 dyna 28 0 352 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries the total length of the request is the length of the dynamic string plus the text of the request len 28 reqLength puts the dynamic string into the transmit buffer Ethernet putByrtesitdyna 28 2 then puts the request string converted into upper char into the transmit buffer while regLength Spi Ethernet putbytei itoupperi2pi Ethernet geteytets return len back to the library with the length of the UDP reply E main entry void main starts 2876 with 512 on PI S io 1 my amp IP address full duplex Ar Spi Init Advanced MASTER OSC DIV16 CLK IDLE LOW IDLE 2 ACTIVE DATA ORDER MSB Ethernet mylpaAddr Spi Ethernet FULLDI PLEX full duplex CRC MAC Unicast MAC Broadcast filtering while 1 do forever if necessary test the return value to get error code Spi Ethernet doPacket 2 process incoming Ethernet packets add your stuff here if needed EchernH r doPackert must cdlled often possible otherwise packets could be lost er 2 2 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 359 CHAPTER 6 Libraries mi
34. 401 SPI TO963C TEX one ree edges ee dee 401 Spl_16963C_CUISOF Reed CR ee de ER 402 Spi T6963C Cursor Blink 402 Library 402 HW Connection 407 T6963C Graphic LCD Library 408 External dependencies of T6963C Graphic LCD Library 409 Library ROUES C ee ttdi veh A oa gee 410 TOJO Misser epee hoe eee EA base Reese Lease 411 xxii MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 Table of Contents 6963 WriteData 412 6963 _ 412 TOJO SCIP teen cc codices vowed 413 T6963C_WaitReady 413 TOI SC Fil he a ee 413 TOC DOl Hees peed pra te eee dee eres 414 6963 _ _ 414 6963 _ _ 415 TOS5SC LING C HEC ORE CUERO ROS CR ORE dos car 416 T6963C_Rectangle 416 TOSD3SC BOX saca oru dde dob aca ew bare w
35. DEEI Number of bytes written into ENc28360 RAM Description This is MAC module routine It stores whole string excluding null termination into Nc28760 RAM starting from current ENC28J60 write pointer EwRPT location Parameters ptr String to be written into ENc28760 RAM Ethernet module has to be initialized See Spi Ethernet Init Example char bu ulfer mikroElektronika Spi Ethernet putString buffer put a RAM string into ENC28J60 buffer 342 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi_Ethernet_putConstString Prototype unsigned int Spi Ethernet putConstString const unsigned char ptr Number of bytes written into ENc28760 RAM Description This is MAC module routine It stores whole const string exclud ing null termination into z c28560 RAM starting from current ENC28J60 write pointer EwRPT location Parameters ptr const string to be written into ENc28760 RAM Requires Ethernet module has to be initialized See Spi Ethernet Init Example const char buffer mikroElektronika Spi Ethernet putConstString buffer put a const string into ENCZ28J60 buffer Spi Ethernet getByte Prototype unsigned char 5pi Ethernet getByte Byte read from ENc28760 RAM Description This is MAC module routine It fetches a byte from address pointed to by current ENc28 60 read pointer ERDPT Ethernet module has to be
36. Example OxlAC30F4 tmp Lo d Equals OxF4 Hi Returns next to the lowest byte of number bits 8 15 Description Function returns the lowest byte of number Function does not interpret bit patterns of number it merely returns 8 bits as found in register This is an inline routine code is generated the place of the call so the call doesn t count against the nested call limit Requires Arguments must be variable of scalar type 1 Arithmetic Types and Pointers Example d tmp Hi d Equals 0x30 104 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroC for 8051 Specifics Higher Returns next to the highest byte of number bits 16 23 Description Function returns next to the highest byte of number Function does not interpret bit patterns of number it merely returns 8 bits as found in register This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Requires Arguments must be variable of scalar type 1 e Arithmetic Types and Pointers Example d OxlAC30F4 tmp Higher d Equals Highest Returns the highest byte of number bits 24 31 Description Function returns next to the highest byte of number Function does not interpret bit patterns of number it merely returns 8 bits as found in register This is an inline
37. MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 213 CHAPTER 5 Language Reference mikroC for 8051 It is highly recommended to put parentheses around each argument in the macro body in order to avoid possible problems with operator precedence Undefining Macros The unaet directive is used to undefine a macro undef macro identifier The directive undef detaches any previous token sequence from macro identi fier the macro definition has been forgotten and macro identifier 15 undefined No macro expansion occurs within the undef lines The state of being defined or undefined is an important property of an identifier regardless of the actual definition The ifdef and ifndef conditional directives used to test whether any identifier 15 currently defined or not offer a flexible mech anism for controlling many aspects of a compilation After a macro identifier has been undefined it can be redefined with define using the same or different token sequence FILE INCLUSION The preprocessor directive include pulls header files extension n into the source code Do not rely on preprocessor to include source files extension c see Add Remove Files from Project for more information The syntax of the include directive has two formats include lt header name gt include header name The preprocessor removes the include line and replaces it with the entire text of a h
38. Note Library functions are blocking call functions they are waiting for clock line to become logical one Note The pins used for communication should be connected to the pull up resis tors Turning off the LEDs connected to these pins may also be required External dependecies of Soft_I2C Library The following vari ables must be defined in all projects using Soft I2C Library Description Example extern Soft PC Clock line Soft I2C Scl SOIL IZO SOL at Pl B3g extern sbit Soft PC Data line Soft I2C Sda sbit Soft I2C Sda at P1 B4 Library Routines Soft I2C Init Soft I2C Start Soft I2C Read Soft I2C Write Soft I2C Stop MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 311 CHAPTER 6 Libraries mikroC for 8051 Soft I2C Init Prototype Sort Init Nothing Configures the software module Requires Soft 2C Sci and Soft 2 variables must be defined before using this function Example 120 pinout derinition SOLE 501 at Pl B3 SDLE Sort 120 at PI B4 Soft T20 Init Soft_I2C Start Requires Software PC must be configured before using this function See soft I2C Init routine Example Issue START signal OOIL Carti Soft 2 Read Prototype unsigned short Soft I2C Read unsigned int ack One byte from the Slave Description Reads one byte from the
39. Spi T6963C Text Description Enable disable text displaying Parameters n text enable disable parameter Valid values 0 disable text dispaying and 1 enable text displaying Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example enable text displaying 1859020 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 401 CHAPTER 6 Libraries mikroC for 8051 Spi T6963C Cursor Penn Description Set cursor on off Parameters n on off parameter Valid values 0 set cursor off and 1 set cursor on Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example enable text displaying pL Spi T6963C Cursor Blink Prototype void Spi T6963C Cursor Blink char n Description Enable disable cursor blinking Parameters n Cursor blinking enable disable parameter Valid values 0 disable cursor blinking and 1 enable cursor blinking Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example enable cursor blinking 753530 Cursor Library Example The following drawing demo tests advanced routines of the Spi T6963C GLCD library Hardware configurations in this example are made for the T6963C 240x128 display Easy8051B board and AT8988253 402 MIKROELEKTRONIKA SOFTWA
40. UART LIBRARY The UART hardware module is available with a number of 8051 compliant MCUs The mikroC for 8051 UART Library provides comfortable work with the Asynchronous full duplex mode Library Routines Uart Init Uart Data Ready Uart Read Uart Write Uart_Init Prototype void Uart Init unsigned long baud rate Description Configures and initializes the UART module The internal UART module module 15 set to 8 bit data no parity STOP bit disabled automatic address recognition timer as baudrate source mod2 autoreload 8bit timer Parameters baud_rate requested baud rate Refer to the device data sheet for baud rates allowed for specific Fosc MCU with the UART module and TIMER to be used as baudrate source Example Initialize hardware UART and establish communica tion at 2400 Init 24D0 432 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Uart_Data_Ready Prototype char Uart Data Ready Returns 1 if data is ready for reading 0 if there is no data in the receive register The function tests if data in receive buffer is ready for reading Requires MCU with the UART module The UART module must be initialized before using this routine See the Uart Init routine Example char receive AP data if ready ir Data receive Uart Read Uart_Read Prot
41. bacolor pink gt BUTTON ATHA 33 if P0 amp 1 lt lt i str lt td bgcolor red ONN jN else str lt td bgcolor cccccc gt OFF stir sh document write str lt Ww 4 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 347 CHAPTER 6 Libraries mikroC for 8051 const char indexPage2 lt table gt lt td gt lt td gt lt table border 1 style font size 20px font family terminal gt lt Cre lt th colspan 3 gt P3 lt the lt 7 tr norint var m for 1 021 lt 6714 strt lt tr gt lt td bgcolor yellow gt LED it lt td gt af lt td buaecolorered DNA else str lt td bgcolor cccccc gt OFF strt lt td gt lt td gt lt a href t it gt Toggle lt a gt lt td gt lt tr gt s document write str lt script gt cJtahlesec tue teec rable This is HTTP request lt script gt document write REQ lt script gt lt BODY gt lt HTML gt OK KKK KK RK KK KK KK KK KK KK KK kk ok RAM variables a idata unsigned char myMacAddr 6 0x00 14 OxA5 0 76 0 19 xST my MAC address idata unsigned char mylpAadr 4 my IP address 1124 189 1 BO 7 idata unsigned char getRequest 15 HTTP request buffer idata unsigned char dyna 29 buffer for dynamic response idata unsigned long
42. duplex config flags define Spi Ethernet HALFDUPLEX 0x00 half duplex define Spi Ethernet FULLDUPLEX 0x01 full duplex mE ehternet NIC pinout sfr sbit Spi Ethernet RST at P1 B0 sfr sbit Spi Ethernet CS at end ethernet NIC definitions OK KKK KK KK KK I KK KK IK KK IK KK KR KK IKK KK KK KK KK KK ROM Constant strings Pr const code unsigned char httpHeader HTTP 1 1 200 OK nContent type HTTP header const code unsigned char httpMimeTypeHTMI text html n n HTML MIME type const code unsigned char httpMimeTypeScript 1 TEXT MIME type idata unsigned char httpMethod 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 code char indexPage Change the IP address of the page to be refreshed lt meta http equiv refresh contente lt HTML gt lt HEAD gt lt HEAD gt lt BODY gt lt 1 gt 8051 ENC28J60 Mini Web Server lt h1 gt hret gt Reload lt a gt lt script src s gt lt script gt lt table gt lt tr gt lt td gt lt table border 1 style font size 20px font family terminal gt tro th colepan 2 gt P0 lt th gt lt tr gt lt Scri pie str for 1 0 1 lt 8 1 atria
43. tifier The label identifier has to be a name of the label within the same function in which the goto statement 15 The goto line can come before or after the label 208 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference goto 1s used to break out from any level of nested control structures but it cannot be used to jump into block while skipping that block s initializations for example jumping into loop s body etc The use of goto statement 15 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 for 1 22 2721 1f disaster goto Error Bonne error handling code RETURN STATEMENT The return statement is used to exit from the current function back to the calling rou tine optionally returning a value The syntax 1s return expression This will evaluate expression and return the result Returned value will be auto matically converted to the expected function type if needed The expression 1s optional if omitted the function will return a random value from memory Note The statement return in functions of the void type cannot have expression in fact the return statement can be omitted altogether if it is the last statement in the function body COMPO
44. vrm 176 3535555 1 hag pads Haws eee 177 Static aan a we 177 EXC 64 177 Type 177 Qualifier const 177 Qualifier volatile 178 Typedef Specifier 178 asm Declaration 179 huius twa wena ete ona Go ee ee oe ek ee fae eed a 180 Automatic Initialization 181 FONCIONS 181 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 Table of Contents Function Declaration 182 Function Prototypes ii oust earned eh Mh bare Fab RE oh 182 Function Definition 183 Functions reentrancy 194 Function Calls and Argument Conversions 184 PURCHON CANS 184 Argument Conversions 185 186 ODEIO sord
45. 11 e ii 11 Fill data buffer Eeprom Write 2 0xAA Write some data at address 2 Eeprom Write 0x732 0x55 Write some data at address 0x732 Eeprom Write Block 0x100 dat Write 32 bytes block at address 0 100 Delay ms 1000 Blink PO and P1 diodes OxFF to indicate reading start Pl OxFF Delay 1000 0 00 Pl 0x00 Delay ms 1000 Read 4 Read data from address 2 and display it on PORTO PI Repnrom BesadiUux 32 Read data from address 0x732 and display it on 1 Delay 1000 for ii 9 11 22 iit 4 Read 32 bytes block from address 0x100 Pe Readg 0xlD0 11 and display data on PORT2 Delay ms 500 242 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries GRAPHIC LCD LIBRARY The mikroC for 8051 provides a library for operating Graphic LCD 128x64 with commonly used Samsung KS108 KS107 controller For creating a custom set of GLCD images use GLCD Bitmap Editor Tool External dependencies of Graphic LCD Library The following variables must be defined in all projects using Graphic Description Example LCD Library extern volatile sfr LCD Data Port sfr char GLCD DataPort char GLCD DataPort at extern sbit GLCD CS1 Chip Select 1 line shit GLCD CSI at P2 50 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
46. D 4 WHITE 3 163630 box 0 119 2239 127 T53953C WHITE 7 Draw circles 7 T6Sb2C Garcle 140 64 I0 Teleco WAITE T6963L circle 120y G4 20 T59520 WHITES 140 564 50 TONO C WEITE T6963C circle 120 64 70 T6963C WHITE I56SP3SC paircle lzU G4 90 TOC NHITE T6963L clrele l20 542 110 TGDC WHITE 2 TC903C cilrclellz0 84 TOSOSC WHITE 7 428 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 roots SPELLS lity 4 1696026 SeLtCcrPaneltl 7 PTOSbSU Sprite me Fill the graphic screen 6963 image mc foriri JU Uo 182 pressed einstein CHAPTER 6 Libraries 590 117 2 Draw a sprite Select other graphic panel 128 4j with a picture Endless loop toggle the display between graphic panel 0 and graphic 1 9 panel panel amp 1 T6906207 displayCcrP nelipeanel Delay ms 300 7 SOLE Fe I 285 preced Ry else if P2 1 T6UPOC Graphics 1 Toons Delay ms 300 Fil IF PS 2 DIOSSSOC ey else if P2 2 T6563U Graphics 9 Delay 300 7 n LE OPI 2 28 DIressec else 1 2 3 TO9b52U graphicsil Delay ms 300
47. Delay25S for ii 5 ii lt 60 iit 5 delay ms 250 7 olod V 38 212 172 E laneis 120 Delay25S epi 2100 Pall 000 7 mikroC for 8051 Initialize GLCD Jf Clear CLOD Draw image 7 Draw box Draw rectangle Draw line yz Draw hordzsontal and vertical Jine Spi Glcd Set Font Character8x8 8 8 32 Choose font see _ Lib GLUDFOnLtS o in Uses folder 2100 Write Testi meron 9 Tee 22 for ii 1 11 lt 10 11 opa Glod Cirele C3 34 2231 20 Delay2S Gilead Boxilsz U 22 0 274 Delay25S opi Set FontiFont2oystenmoxb 2 9 someText BIG LETTERS 2100 Write 5 2 27 Delay25S someText SMALL NOT SMALLER spl Gled Write Tex ecielert 20 5 102 Delay2S Write string J Draw circles Draw box 32 Change font Write string Write string 368 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries HW Connection vcc VCC 23517 wu Ta CS2 li TE 19 1 0 GC8S681V Left side Right side X AX S Contrast Adjustment Vo _ 6 13 SPI GLCD HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 369 CHAPTER 6 Libraries mikroC for 8051 SPI LCD LIBRARY
48. E 450 cpi Mr 450 ipso P ee 450 cul L rrr 450 450 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XXV Table of Contents mikroC for 8051 SUNCOY Ghee eed 5 4 ede 451 SIS Ansa ore ees yn creek a ee wa a 451 451 451 CSDM Gate dad ae eh ee ee ee See eee 452 ee gene ed ee mae gee ar eee S E EE 452 Bog hoes eon Sek ae Au 452 Button LIDrary AM deh do deh doa dee we he a ee 453 External dependecies of Button Library 453 Library ROUUNCS uuu 04000e n Ram Rd gro ded eed a andes 453 DUTON rr 454 Conversions 455 sata won sees ok cates 455 BVE IOS annua tenes oe boo eed end es eee ae 4 455 SOIL IOS 456 WOrd ended eee ate 456 nj a ose oe eet ee es eee ee ees be ee ee bate 457 Bele seca Be bee eee eee 457 LongWordToStr 458 FICAUIOOW 342552152655
49. Functions are declared in user s source files or made available by linking precom piled libraries The declaration syntax of the function 1s nemelporamerer declarertore lrist The function name must be a valid identifier This name 15 used to call the func tion see Function Calls for more information type represents the type of function result and can be of any standard or user defined type For functions that do not return value the void type should be used The type can be omitted in global function declarations and function will assume the int type by default Function type can also be a pointer For example float means that a function result is a pointer to float The generic pointer void is also allowed The function cannot return an array or another function Within parentheses parameter declarator list 1s a list of formal arguments that function takes These declarators specify the type of each function parameter The compiler uses this information to check validity of function calls If the list is empty a function does not take any arguments Also if the list 1s void a function also does not take any arguments note that this 15 the only case when void can be used as an argument s type Unlike variable declaration each argument in the list needs its own type specifier and possible qualifier const or volatile Function Prototypes A function can be defined only once in the program
50. Keypad Key Press Keypad Key Click Prototype char Keypad Key Click void Returns The code of a clicked key 1 16 If no key is clicked returns 0 Description Call to Keypad Key Click 1s a blocking call the function waits until some key is pressed and released When released the func tion returns 1 to 16 depending on the key If more than one key is pressed simultaneously the function will wait until all pressed keys are released After that the function will return the code of the first pressed key Requires Port needs to be initialized for working with the Keypad library see Keypad Init Example kp Key 260 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Library Example This is a simple example of using the Keypad Library 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 15 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 unsigned short kp cnt oldstate 0 char txt 5 Keypad module connections sfr char keypadPort at P0 End Keypad module connections lcd pinout definition sbit LCD RS at P2 B0 sbit LCD EN at 2 1 sbit LCD D7 at P2 B5 sbit LCD
51. MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 115 CHAPTER 4 8051 Specifics mikroC for 8051 MEMORY MODELS The memory model determines the default memory type to use for function argu ments automatic variables and declarations that include no explicit memory type The mikroC for 8051 provides three memory models small Compact Large You may also specify the memory model on a function by function basis by adding the memory model to the function declaration small memory model generates the fastest most efficient code This 1s default mem ory model You may override the default memory type imposed by the memory model by explicitly declaring a variable with a memory type specifier Small model In this model all variables by default reside in the internal data memory of the 8051 system as if they were declared explicitly using the data memory type spec ifier In this memory model variable access is very efficient However all objects that are not explicitly located in another memory area and the call stack must fit into the internal RAM Call Stack size 1s critical because the stack space used depends on the nesting depth of the various functions Compact model Using the compact model by default all variables are allocated in a single page 256 bytes of external data memory of the 8051 system as if they were explicitly declared using the pdata memory type specifier This memory
52. Requires LCD needs to be initialized for SPI communication see Spi Led Config routines Example Write character i at row 2 3 Log Chrz 2 7277 372 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi Lcd Chr Prototype void Spi Lcd Chr CP char Out Char Description Prints character on LCD at current cursor position Both variables and literals can be passed as character Parameters Out Char character to be written Requires LCD needs to be initialized for SPI communication see Spi Led Config routines Example Write character i at row 2 column 3 LOS 1746 2 Spi Lcd Description Sends command to LCD Parameters out char command to be sent Note Predefined constants can be passed to the function see Available LCD Commands Requires LCD needs to be initialized for SPI communication see Spi Led Config routines Example Clear LCD display Spi Lcd Cmd LCD CLEAR MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 375 CHAPTER 6 Libraries mikroC for 8051 Available LCD Commands LCD RETURN HOME Return cursor to home position returns a shifted dis play to its original position Display data RAM 15 unaf fected 374 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Library Example This example
53. Transform seconds minutes minutes amp 0 0 gt gt 4 10 minutes amp OxOFP Traneform montbs 314 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 CHAPTER 6 Libraries hours hours amp OxFO0 gt gt 10 hours 6 77 Transform hours year day amp OxXCO gt gt 6 Transform year day amp 0x30 gt gt 4 10 day amp OxOF 77 Transform day month fimonch amp 10 gt gt 2 10 month amp DxOUP Transform month qu ec Ie Output values to LCD void Display Time Lcd Chr 1 6 day 10 48 Print tens digit of day variable Lcd Ohril 7 aay 10 48 Print oness digit of day variable Led Chr l 9 month 7 10 48 Led Chr 1 10 month 5 10 48 Lcd Chril 15 year 56 Print year vaiable 8 start from year 2008 Lea Chrizy 6 heures 10 48 Led Chr 2 7 hours 10 48 Led ODri2 5 minutes 10 48 Led Chrig lO iminutes L0 48 Chri 2 12 seconde 7 10 48 hed Chr 2 13 seconds 10 48 void Init Main Sort Init Led Init Lcd LCD CLEAR Lcd LCD CURSOR OFF tcp cud LCD Chri LGD LEES LCD OUT 195 irl LCD Chr do LED Ubris LCD Out 1 T T MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Dater ys 1 I4 Tine 7 A 2733 TO
54. after first cali fs sel 2 after second call ael De efter third coll etc TYPES The mikroC for 8051 is a strictly typed language which means that every object function and expression must have a strictly defined type known in the time of compilation Note that the mikroC for 8051 works exclusively with numeric types The type serves to determine the correct memory allocation required initially to interpret the bit patterns found in the object during subsequent access in many type checking situations to ensure that illegal assignments are trapped The mikroC for 8051 supports many standard predefined and user defined data types including signed and unsigned integers in various sizes floating point num bers with various precisions arrays structures and unions In addition pointers to most of these objects can be established and manipulated in memory MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 145 CHAPTER 5 Language Reference mikroC for 8051 The type determines how much memory 15 allocated to an object and how the pro gram will interpret the bit patterns found in the object s storage allocation A given data type can be viewed as a set of values often implementation dependent that identifiers of that type can assume together with a set of operations allowed with these values The compile time operator sizeof allows you to determine the size
55. and function return values bit bf bit variable All bit variables are stored in a bit addressable portion 0x20 0x2F segment located in the internal memory area of the 8051 Because this area is only 16 bytes long a maximum of 128 bit variables may be declared within any one scope There are no pointers to bit variables bait invalid An array of type bit 1s not valid bit arr 5 77 invalid Bit variables can not be initialized nor they can be members of structures and unions Related topics Bit fields Predefined globals and constants 100 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroC for 8051 Specifics INTERRUPTS 8051 derivates acknowledges an interrupt request by executing a hardware generat ed LCALL 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 address of Timer 0 Overflow interrupt source of the AT89S8253 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 per forms smart context switching between them two saving only the registers that have been us
56. mikroC for 8051 Language Reference Register At the moment the modifier register technically has no special meaning The mikroC for 8051 compiler simply ignores requests for register allocation Static A global name declared with the static specifier has internal linkage meaning that it is local for a given file See Linkage for more information A local name declared with the static specifier has static duration Use static with a local variable to preserve the last value between successive calls to that func tion See Duration for more information Extern A name declared with the extern specifier has external linkage unless it has been previously declared as having internal linkage A declaration is not a definition if it has the extern specifier and is not initialized The keyword extern 1s optional for a function prototype Use the extern modifier to indicate that the actual storage and initial value of the variable or body of the function 15 defined in a separate source code module Functions declared with extern are visible throughout all source files in the pro gram unless the function is redefined as static See Linkage for more information TYPE QUALIFIERS The type qualifiers const and volatile are optional in declarations and do not actu ally affect the type of declared object Qualifier const The qualifier const implies that a declared object will not change its value during runtime In declarations
57. operators PREPROCESSOR DIRECTIVES Any line in the source code with a leading is taken as a preprocessing directive or control line unless is within a string literal in a character constant or embedded in a comment The initial can be preceded or followed by a whitespace excluding new lines A null directive consists of a line containing the single character This line 15 always ignored Preprocessor directives are usually placed at the beginning of the source code but they can legally appear at any point in a program The mikroC for 8051 preproces sor detects preprocessor directives and parses the tokens embedded in them A direc tive is in effect from its declaration to the end of the program file 210 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference Here is one commonly used directive Finclude lt math h gt For more information on including files with the include directive refer to File Inclusion The mikroC for 8051 supports standard preprocessor directives null directive if define ifdef elif ifndef else include endif 1 undef Note For the time being only funcall pragma is supported Line Continuation with Backslash To break directive into multiple lines end the line with a backslash Pdefine MACRO This directive continues to the following line MACROS Macros provide
58. sbit SoftSpi SDI at PO B4 SoftSpi SDI extern sbit Data Out line sbit SoftSpi SDO at P0 B5 SoftSpi SDO _ t bit extern sbi Clock line sbit SoftSpi at SoftSpi CLK _ Library Routines Soft Spi Init Soft Spi Read Soft Spi Write MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 317 CHAPTER 6 Libraries mikroC for 8051 Soft_Spi_Init Configures and initializes the software SPI module Requires SoftSpi CLK Softspi SDI and softspi sro variables must be defined before using this function Example soft spi pinout definition sbit SoftSpi SDI at 4 sbit SoftSpi SDO at PU B5 sbit SoftSpi CLK at PD B3 SOIL SPI _ Sort SPI Soft Spi Read Prototype unsigned short Soft Spi Read char sdata Byte received via the SPI bus Description This routine performs 3 operations simultaneously It provides clock for the Software SPI bus reads a byte and sends a byte Parameters sdata data to be sent Requires Soft SPI must be initialized before using this function See Soft Spi Init routine Example unsigned short data reag char data send Read byte and assign it to data read variable data send byte will be sent via SPI during the Read operation read e port Spi Readidata send 318 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Soft_Spi_ Write Pr
59. unsigned short y upper left unsigned short x bot tom right unsigned short y bottom right unsigned short color Description Draws a rectangle on GLCD Parameters x upper left X coordinate of the upper left rectangle corner Valid values 0 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right X coordinate of the lower right rectangle cor ner Valid values 0 127 y bottom right y coordinate of the lower right rectangle cor ner Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the color of the rectangle bor der 0 white 1 black and 2 inverts each dot Requires GLCD needs to be initialized see Init routine Example Draw a rectangle between dots 5 5 and 40 40 Glod Rectangle 5 49 40 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 251 CHAPTER 6 Libraries mikroC for 8051 Glcd Box Prototype void Glcd Box unsigned short x upper left unsigned short y upper left unsigned short x bottom right unsigned short y bottom right unsigned short color Description Draws a box on GLCD Parameters x upper left X coordinate of the upper left box corner Valid values 0 127 y upper left y coordinate of the upper left box corner Valid values 0 63 x bottom right X coordinate of the lower right box corner Valid values 0 127 y bot
60. void Vdelay ms unsigned time in ms Nothing Creates a software delay in duration of time in ms millisec onds a variable Generated delay is not as precise as the delay created by Delay ms Note that vae1ay ms is library function rather than a built in routine it is presented in this topic for the sake of conven pause 1000 Or o Vdelay ms pause 44 one second pause void Delay Cyc char Cycles div by 10 Creates a delay based on MCU clock Delay lasts for 10 times the input parameter in MCU cycles Note that Delay is library function rather than a built in routine it is presented in this topic for the sake of conven There are limitations for cycles div 10 value Value cycles div by 10 must be between 2 and 257 Delay Cyc 10 Hundred MCU cycles pause MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 107 CHAPTER 3 Specifics mikroC for 8051 Clock Khz Device clock in KHz rounded to the nearest integer Description Function returns device clock in KHz rounded to the nearest integer This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Example Delay Cyc 10 Hundred MCU cycles pause Clock Mhz Device clock in MHz rounded to the nearest integer Description Function returns device clock in MHz rounded to the nearest integer This i
61. y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values Spi 6963 BLACK and Spi T69635C WHITE Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example 5 6963 Rectangle 20 20 219 107 T6963C WHITE 392 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi_T6963C_Box Prototype void Spi 6963 Box int x0 int yO int xl int yl unsigned char pcolor Description Draws a box on the GLCD Parameters x0 X coordinate of the upper left box corner y0 y coordinate of the upper left box corner x1 X coordinate of the lower right box corner yl y coordinate of the lower right box corner pcolor color parameter Valid values Spi T6963C BLACK and Spi T6963C WHITE Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Spi T6963C Box 0 119 239 127 T6963C WHITE Spi T6963C Circle Prototype void Spi T6963C Circle int x int y long r unsigned char pcolor Description Draws a circle on the GLCD Parameters x X coordinate of the circle center y y coordinate of the circle center r radius size pcolor color parameter Valid values Spi 6963 BLACK and Spi T6963C WHITE Requires T
62. 243 CHAPTER 6 Libraries mikroC for 8051 Library Routines Basic routines Gled_Init Gled Set Side Gled Set X Gled Set Page Gled Read Data Gled Write Data Advanced routines Gled Fill Gled Dot Gled Line Gled V Line Gled H Line Gled Rectangle Gled Box Gled Circle Gled Set Font Gled Write Char Gled Write Text Gled Image 244 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Glcd Init Description Initializes the GLCD module Each of the control lines is both port and pin configurable while data lines must be on a single port pins lt 0 7 gt Requires Global variables GLCD 1 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 EN enable Sun pin GLCD reset signal pin GLCD DataPort data port must be defined before using this function Example 1 pinout settings sfr char GLCD DataPort at P0 sbit GLCD CS1 at sbit GLCD CS2 at sbit GLCD RS at v sbit GLCD RW at 4127 sbit GLCD RST at sbit GLCD at P2 B4 Gica Initir MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 245 CHAPTER 6 Libraries mikroC for 8051 Glcd Set Side Prototype void Glcd Set Side unsigned short x pos Description Selects GLCD side Refer to the GLCD datashe
63. 3 3 Spi Led_Cmd 3 3 Available LCD Commands 374 Library Example 22433 eet dee ee cue nk eee dee mark teres 4 one 375 HW Connection 376 SPI LCD8 8 bit interface Library 377 Library ROUES died dean oe ee 377 Sol COMNG 378 Spl ECHO OU equo EA 378 Spi ewan PRO E 379 SPL LCOS CH 522255 379 Pedo CH D 380 Sol cdo OMG 380 Available LCD Commands 381 Library 382 HW Connection 222a nnus 383 SPI T6963C Graphic LCD Library 384 Library ROUUNES APT 385 ois e PESO 386 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Table of Contents mikroC for 8051 T6963C WriteData 387 T6963C WriteCommand 387 Spi 16963C bee od nee be he Sos 388 opr T6963C Warnlseady 388 T6969C Fill
64. 80 extern sbit CanSpi Rst Reset line sbit CanSpi Rst at P1 B2 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 223 CHAPTER 6 Libraries mikroC for 8051 Library Routines CANSPISetOperationMode CANSPIGetOperationMode CANSPIInitialize CANSPISetBaudRate CANSPISetMask CANSPISetFilter CANSPIread CANSPI Write The following routines are for an internal use by the library only RegsToCANSPHD CANSPIIDToRegs Be sure to check CANSPI constants necessary for using some of the functions CANSPISetOperationMode Prototype void CANSPISetOperationMode char mode char WAIT Description Sets the CANSPI module to requested mode Parameters mode CANSPI module operation mode Valid values can SPI MODE constants see CANSPI constants WAIT CANSPI mode switching verification request If wart 0 the call is non blocking The function does not verify if the CANSPI module is switched to requested mode or not Caller must use CANSPIGetOperationMode to verify correct operation mode before performing mode specific operation If WAIT 0 the call is blocking the function won t return until the requested mode 15 set Requires nu routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page Example set the CAN
65. ALL OTHER WARRANTIES AND CONDITIONS EITHER EXPRESSED OR IMPLIED INCLUDED BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE TITLE AND NON INFRINGEMENT WITH REGARD TO SOFTWARE AND THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES IN NO EVENT SHALL MIKROELEKTRONIKA ASSOCIATES OR ITS SUPPLI ERS BE LIABLE FOR ANY SPECIAL INCIDENTAL INDIRECT OR CONSE QUENTIAL DAMAGES WHATSOEVER INCLUDING WITHOUT LIMITA TION DAMAGES FOR LOSS OF BUSINESS PROFITS AND BUSINESS INFORMATION BUSINESS INTERRUPTION OR ANY OTHER PECUNIARY LOSS ARISING MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 Introduction mikroC for 8051 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 MIKROELEK TRONIKA ASSOCIATES ENTIRE LIABILITY UNDER ANY PROVISION OF THIS LICENSE AGREEMENT SHALL BE LIMITED TO THE AMOUNT ACTU ALLY PAID BY YOU FOR SOFTWARE PRODUCT PROVIDED HOWEVER IF YOU HAVE ENTERED INTO A MIKROELEKTRONIKA ASSOCIATES SUP PORT SERVICES AGREEMENT MIKROELEKTRONIKA ASSOCIATES ENTIRE LIABILITY REGARDING SUPPORT SERVICES SHALL BE GOV ERNED BY THE TERMS OF THAT AGREEMENT HIGH RISK ACTIVITIES Software is not fault tolerant and is not designed manufactured or intended for use or resale as on line control e
66. AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries BUTTON LIBRARY The Button library contains miscellaneous routines useful for a project develop ment External dependecies of Button Library The following vari able must be defined in all projects using Button library Description Example Declares Button_ Pin which will be used by sbit Button Pin at 0 Button Library extern sbit Button Pin Library Routines Button MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 453 CHAPTER 6 Libraries mikroC for 8051 Button Prototype unsigned short Button unsigned short time unsigned short active starte Returns 255 if the pin was in the active state for given period 0 otherwise Description The function eliminates the influence of contact flickering upon pressing a button debouncing The Button pin is tested just after the function call and then again after the debouncing period has expired If the pin was in the active state in both cases then the function returns 255 true Parameters time debouncing period in milliseconds active state determines what is considered as active state Valid values 0 logical zero and logical one Requires Button Pin variable must be defined before using this function Button pin must be configured as input Example 2 is inverted on every one to zero transition Button con
67. About MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 31 CHAPTER 2 Environment mikroC for 8051 Fi Open Help File Quick Help Check if new compiler version 15 available Check For Updates Open mikroElektronika Support Forums in mikraElekkronika Support Forums adele Open mikroElektronika Web Page in a mikraElekEranika Web Page distat denos eder How To Register Information on how to register About Open About window Related topics Keyboard shortcuts KEYBOARD SHORTCUTS Below is a complete list of keyboard shortcuts available in mikroC for 8051 IDE You can also view keyboard shortcuts the Code Explorer window tab Keyboard IDE Shortcuts A Ctrl Shift O Open Project Ctrl Shift N Open New Project 32 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Basic Editor Shortcuts Ctrl Y Delete entire line MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 33 CHAPTER 2 Environment mikroC for 8051 34 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment cu MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 35 CHAPTER 2 Environment mikroC for 8051 IDE OVERVIEW The mikroC for 8051 is an user friendly and intuitive environment mikrot for 8051 C Program FilesWikroelektronikaWnikroC 80
68. DAC chip void main InitMain Perform main initialization 320 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries value 2048 When program starts DAC gives the output in the mid range while 1 Endless loop if value 4095 4 If P0 0 is connected to GND value increment value else Lf 1 e value gt UJ d z7 PU I Z5 connecter value decrement value DAC Output value Perform output Delay ms 10 Slow down key repeat pace MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 321 CHAPTER 6 Libraries mikroC for 8051 SOFTWARE UART LIBRARY The mikroC for 8051 provides routines for implementing Software UART commu nication 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 vari ables must be defined in all projects using Description Example Software UART Library extern sbit Receive line sbit Soft Uart RX at P3 B0 Soft Uart RX extern sbit Transmit line sbit Soft Uart TX at P3 B1 Soft Dart i Library Routi
69. E eee a eee 52 XData 53 Data Memory 53 iData Memory 54 bData Memory 54 PData WEMOY cit dodi dede da n Uo loe t RE cw 55 Special Function Registers 99 General Purpose Registers 56 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD V Table of Contents mikroC for 8051 Memory 56 Memory lt 56 Procedures 57 Procedures Size Window of ROM Memory Allocation 57 Heo 58 Procedures Locations Window 58 Integrated 10015 60 USART Terminal 60 ASOU Galt aerer ad Soon oo ee od eh oe R 61 24 62 7 Segment Display Decoder 63 UDP Terminal s ba aoe 1 TRATTO
70. Expander Set DirectionPortB and Expander Set DirectionPortAB routines Example Write a byte to Port Expander s PORTB Expander Set DirfectionPortB 0 0x005 set expander s portb to be output Expander Write PortB 0 0x55 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 289 CHAPTER 6 Libraries mikroC for 8051 Expander_Write_PortAB Prototype void Expander Write PortAB char ModuleAddress unsigned int Data Returns Nothing Description The function writes word to Port Expander s ports Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written Data to be written to PortA are passed in Data s higher byte Data to be written to PortB are passed in Data s lower byte Requires Port Expander must be initialized See Expander Init Port Expander s PortA and PortB should be configured as outputs See Expander Set DirectionPortA Expander Set DirectionPortB and Expander Set DirectionPortAB routines Example Write a byte to Port Expander s PORTA and PORTB Expander Set DirectionPOFtAB U 0x0000 set expander s porta and portb to be output Expander Write PortAB 0 55 290 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Expander_Set_DirectionPortA Prototype void ul aet DirecrtionPortA obar Modul eAddress char Data Returns Nothing Descripti
71. GLCD Parameters image Image to be displayed Bitmap array be located in both code and RAM memory due to the mikroC for 8051 pointer to const and pointer to RAM equivalency Use the mikroC s integrated GLCD Bitmap Editor menu option Tools GLCD Bitmap Editor to convert image to a constant array suitable for displaying on GLCD Requires GLCD needs to be initialized for SPI communication see Spi Init routines Example 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 using serial to parallel convertor MCP23S17 const code char advanced8051 bmp Port Expander module connections sbit SPExpanderRST at P1 B0 sbit SPExpanderCS at 1 1 End Port Expander module connections void Delay2S 2 seconds delay function Delay ms 2000 void main unsigned short 11 unsigned int jj char someText initialize SPI module Spi Init Advanced MASTER OSC DIV4 IDLE LOW IDLE 2 ACTIVE DATA ORDER MSB MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 367 CHAPTER 6 Libraries Glod via SPI 5100 Fill 0x00 2 while 1 Spi Glcd Image advanced8051 bmp 1 25 1 25 2100 Fill 020 Gpl Gled BOxXI52 40 124 506 1 5100 Reortangleis 94 259 1 3 Gled So 227 01
72. HARDWARE SOLUTIONS FOR EMBEDDED WORLD 75 CHAPTER 2 Environment mikroC for 8051 PROJECTS The mikroC 8051 organizes applications into projects consisting of a single project file extension mcproj and one or more source files extension c MikroC for 8051 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 memory model device flags config word device clock list of the project source files with paths header files h binary files mcl image files other files Note that the project does not include files in the same way as preprocessor does see Add Remove Files from Project NEW PROJECT The easiest way to create a project is by means of the New Project Wizard drop down menu Project gt New Project or by clicking the New Project Icon 5 from Project Toolbar New Project Wizard Steps 76 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Step One Provides basic information on settings in the following steps Welcome to the New Project Wizard This wizard helps you e Create 4 new project Selectthe device for your project e Setup device clock and choose device flags 222 Select desired memory model Add
73. Ihe T EIS ede dbs ved EE 388 ODL 389 opi T6963C Write 390 Spi T6963C Write Text 391 Spi 16963C LNE PEE 392 opi T6963C Rectangle 392 ODUI 16969C 22252 393 Spl 169636 393 SDI _ T6963C_lmage 394 5 10908C ee ease Rese 394 Spi T6963C Set CUSO 25525221 395 Spi T6963C ClearBit 395 Spi T69596 SetBit Pa TRIS VOU RIA weno ees 396 Spl _T6963C_NegBit 396 opi T6963C DisplayGrPanel 397 opi T6963C 397 opi T6963C SetGrPanel 398 opi T6963C 398 Spi_T6963C_PanelFill 399 SPI 69656 ITI uus gerent porti di ies anb va eee EENE 399 ODI 16963C TXUMI adc 400 Spi T6963C Cursor Height usui dre x3 ERE 400 T6963C Graphics
74. Image Files sample jpg Output Files 25 6963 240x128 hex 25 T6963C 240x128 asm z T69630 240xlz8 lst 2 473 Other Files g DS AT8958253 dac3286 pdf MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 81 CHAPTER 2 Environment mikroC for 8051 The list of relevant source files is stored in the project file extension mcpro To add source file to the project click the Add File to Project Icon 2 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 cot Note For inclusion of the header files extension h use the preprocessor directive include See File Inclusion for more information Related topics Project Manager Project Settings Memory Model Source Files Source files containing C code should have the extension The list of source files relevant to the application is stored in project file with extension mcproj along with other project information You can compile source files only if they are part of the project Use the preprocessor directive include to include header files with the extension h Do not rely on the preprocessor to include source files other than headers see Add Remove Files from Project for more information MANAGING SOURCE FILES Creating new source file To create a new source file do the following
75. Line Prototype void T5965C Line int ant y ant xl int yl unsigned char pcolor Description Draws a line from x0 y0 to x1 yl 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 T6963C BLACK and T6963C WHITE Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine T6963C Line 0 0 239 127 T6963C WHITE T6963C Rectangle Prototype void T6963C Rectangle int xU int int zl int yl unsigned char pcolor Description Draws a rectangle on GLCD Parameters x0 X coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values T6963C BLACK and T6963C WHITE Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Example 16963 Rectangle 20 20 219 107 T6963C WHITE 416 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries T6963C_Box Prototype void T6 63C Box int int int xl int yl unsigned char pcolor Description Draws a box on GLCD Parameters x0 X coordinate of the upper left box corner y0 y coordinate
76. Operator gt s not applicable to this operands 551 Assigning to non lvalue 5 Cannot cast 251 to 551 Cannot assign 251 to 551 value required Pointer required Argument is out of range Undeclared identifier 5 in expression Too many initializers Cannot establish this baud rate at 5 1 MHz clock Stack overflow Invalid operator Expected variable but constant found Expected constant but 551 found Ss cannot be used outside a loop Unknown type 551 Variable s is redeclared Demo Limit Ss has already been declared 251 Type mismatch expected 2 1 but gt s found File gt s not found 96 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment There is not enough RAM space for all variables There is not enough ROM space Invalid type in array Path to your project c 1 error Not a header name 3s include 251 s error in preprocessor Division by zero Incompatible types 251 5 Assembler instruction 5 was not found Project name must be specified Unknown commmand line Option 251 File exstension missing 251 Bad FO argument 251 Preprocessor exited with error code 551 Bad absolute address 551 Recursion cross calling 251 No files specifed Device parame
77. Ps2 Key Read unsigned short value unsigned short special unsigned short pressed Returns 1 if reading of a key from the keyboard was successful 0 1f no key was pressed Description The function retrieves information on key pressed Parameters value holds the value of the key pressed For characters numerals punctuation marks and space value will store the appropriate ASCII code Routine recognizes the function of Shift and Caps Lock and behaves appropriately For special function keys see Special Function Keys Table special 1s a flag for special function keys F1 Enter Esc etc If key pressed 15 one of these special will be set to 1 otherwise pressed is set to 1 if the key is pressed and 0 if it is released Requires PS 2 keyboard needs to be initialized See 52 Config routine Example unsigned short value special pressed Press Enter to continue do af Pose Rey Beadi value especial amp pressed 4 1f value 13 amp amp special 1 break while 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 297 CHAPTER 6 Libraries mikroC for 8051 Special Function Keys s 6 7 8 9 1 1 1 F DIN 298 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 0 1 2 5 7 10 11 12 13 14 15 16 17 18 19 20 21 2 CHAPTER 6 mikroC for 8051 Libraries Library Example This simple examp
78. SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries CANSPI LIBRARY The SPI module is available with a number of the 8051 compliant MCUs The mikroC for 8051 provides a library driver for working with mikroElektronika s CANSPI Add on boards with MCP2515 or MCP2510 via SPI interface The CAN is a very robust protocol that has error detection and signalization self checking and fault confinement Faulty CAN data and remote frames are re transmitted automatically similar to the Ethernet 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 1s 200Kbit s Cables used are shielded twisted pairs CAN supports two message formats Standard format with 11 1dentifier bits and Extended format with 29 identifier bits Note Consult the CAN standard about CAN bus termination resistance 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 External dependecies of CANSPI Library The following variables must be defined in all projects using Description Example CANSPI Library extern sbit CanSpi CS Chip Select line sbit CanSpi CS
79. SOUNA LIDA od nes eee 325 External dependencies of Sound Library 325 Library Routines 325 SOUNA Jit 2222222 EE 326 Play sus edu cease eee EE n d SR ERE SN 326 Library 326 The example is a simpl 326 demonstration 326 HW Connection 328 329 Library ROUUNES c c 329 Ol AMG 329 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD X1X Table of Contents mikroC for 8051 opi Init 330 SP REAO ao 4224605065460 6 e508 331 vom Ug T 331 ODay EXaMDIG te nH ee 331 23 acu oc 2 3 acad Door E EE C84 ee sobs 999 SPl Ethernet LIBrary eus a 334 External dependencies of SPI Ethernet Library 395 Library Routines 935 Spi Ethernet 336 opi
80. See the T6963C Init routine T595623L yU pocOlOrT T6963C Write Char Prototype void T6963C Write Char unsigned char c IMMUNE char x unsigned char y unsigned char mode Description Writes a char in the current text panel of GLCD at coordinates x y Parameters char to be written x char position on x axis y char position on y axis mode mode parameter Valid values T6963C ROM MODE OR T6963C ROM MODE XOR T6963C ROM MODE AND and T6963C MODE 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 com bined via the logical exclusive OR This can be useful to dis play En in the negative mode 1 e white text on black back groun 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 memo For more details see the T6963C datasheet Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine T6963C Write Char A 22 23 AND 414 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Lib
81. The user accesses to the TCP HTTP request by using some of the Spi Ethernet get routines The user puts data the transmit buffer by using some of the Spi Ethernet put routines The func tion must return the length in bytes of the TCP HTTP reply or 0 if there 1s nothing to transmit If there 1s no need to reply to the TCP HTTP requests just define this function with return 0 as a single statement Parameters remoteHost client s IP address remotePort client s TCP port localPort port to which the request is sent reqLength TCP HTTP request data field length Note The function source code is provided with appropriate example Ie The code should be adjusted by the user to achieve desired reply Requires Ethernet module has to be initialized See Spi Ethernet Init Example This function is internally called by the library and should not be called by the user s code MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 345 CHAPTER 6 Libraries mikroC for 8051 Spi Ethernet UserUDP Prototype unsigned int Spi Ethernet UserUDP unsigned char remoteHost unsigned int remotePort unsigned int destPort unsigned int reqLength Returns 0 there should not be a reply to the request Length of UDP reply data field otherwise Description This is UDP module routine It is internally called by the library The user accesses to the UDP request by using some of the Spi Etherne
82. a mechanism for a token replacement prior to compilation with or without a set of formal function like parameters Defining Macros and Macro Expansions The define directive defines a macro define macro identifier token sequence Each occurrence of macro identifier in the source code following this control line will be replaced in the original position with the possibly empty token sequence there are some exceptions which are discussed later Such replacements are known as macro expansions token sequence 15 sometimes called the body of a macro An empty token sequence results in the removal of each affect ed macro identifier from the source code MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 211 CHAPTER 5 Language Reference mikroC for 8051 No semicolon 15 needed to terminate a preprocessor directive Any character found in the token sequence including semicolons will appear in a macro expan Ssion token sequence terminates at the first non backslashed new line encountered Any sequence of whitespace including comments the token sequence 15 replaced with a single space character After each individual macro expansion a further scan is made of the newly expand ed text This allows the possibility of using nested macros the expanded text can contain macro identifiers that are subject to replacement However 1 the macro expands into something that looks like a preprocessing dire
83. a member of a class put it at the start or end of the list or escape it with a backslash If you want 1 you may place it at the start of list or escape it with a backslash Examples az matches a and az matches z and a z matches and a z matches all twenty six small characters from to 2 n x0D matches any of 10 11 12 13 d t matches any digit or t 1 matches any char from a Metacharacters Metacharacters are special characters which are the essence of regular expressions There are different types of metacharacters described below 70 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Metacharacters Line separators start of line end of line A start of text z end of text any character in line Examples PORTA matches string only if it s at the beginning of line PORTAS matches string PORTA only if it s at the end of line PORTA matches string PORTA only if it s the only string in line PORT r matches strings like PORTB PORT1 and so on The metacharacter by default is only guaranteed to match beginning of the input string text and the metacharacter only at the end Embedded line separators will not be matched by or You may however wish to treat a string as a multi line buffer
84. ap char al temp return al int res void main res addvaratrg l 72 3 4 25 0 7 dddvdrarg l1 2 3 4 5 06 7 9 9 10 00 186 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference OPERATORS Operators are tokens that trigger some computation when applied to variables and other objects an expression Arithmetic Operators Assignment Operators Bitwise Operators Logical Operators Reference Indirect Operators Relational Operators Structure Member Selectors Comma Operator Conditional Operator Array subscript operator Function call operator sizeof Operator Preprocessor Operators OPERATORS PRECEDENCE AND ASSOCIATIVITY There are 15 precedence categories some of them contain only one operator Operators in the same category have equal precedence If duplicates of operators appear the table the first occurrence is unary and the second binary Each category has an associativity rule left to right gt or right to left In the absence of parentheses these rules resolve a grouping of expres sions with operators of equal precedence MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 187 CHAPTER 5 Language Reference mikroC for 8051 Operands Operators Associativity type sizeof 5 2
85. as void which means that they can point to any type These pointers are sometimes called generic DERIVED TYPES The derived types are also known as structured types They are used as elements in creating more complex user defined types The derived types include arrays pointers Structures unions MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD E CHAPTER 5 Language Reference mikroC for 8051 ARRAYS Array is the simplest and most commonly used structured type A variable of array type is actually an array of objects of the same type These objects represent ele ments of an array and are identified by their position in array An array consists of a contiguous region of storage exactly large enough to hold all of its elements Array Declaration Array declaration is similar to variable declaration with the brackets added after identifer array name constant eaxpressionj This declares an array named as array name and composed of elements of type The type can be any scalar type except void user defined type pointer enumeration or another array Result of constant expression Within the brackets determines a number of elements in array If an expression 15 given in an array declarator it must evaluate to a positive constant integer The value is a number of elements in an array Each of the elements of an array 15 indexed from 0 to the number of elements minus one If a n
86. be found in the mikroC for 8051 Time Library Demo example folder Library Routines Time dateToEpoch Time epochToDate Time dateToEpoch Prototype long Time dateToEpoch TimeStruct ts Returns Number of seconds since January 1 1970 OhOOmn00s Description This function returns the unix time number of seconds since January 1 1970 OhOOmn00s Parameters ts time and date value for calculating unix time Example include Time lib kh TimeStruct Eel long epoch what is the epoch of the date in ts Time dateToEpoch amp tsl MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 467 CHAPTER 6 Libraries mikroC for 8051 Time_epochToDate Prototype void Time epochToDate long e TimeStruct ts Description Converts the unix time to time and date Parameters unix time seconds since unix epoch ts time and date structure for storing conversion output Example include TimeStruct long epoch Ja what date is epoch 1234567890 y epoch 1234567890 Time epochToDate epoch amp ts2 468 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Library Example This example demonstrates Time Library usage finclude tinmelib h TimeStr ct tel long epoch long diff void main 0 tsl mn 7 tsl hh 17 tsl md 23
87. break Delay 2 Move cursor even if not visible Sy GDOSXTT AL CDOSX Spi 509532 ExrLols 4 cposx 0 cposyt 4 if cposy Spi T6963C grHeight Spi_T6963C CHARACTER HEIGHT cposy 0 TOYO Ser ocursoficposxz cposy j Delay 406 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries HW Connection gt 7 CO N Contrast Adjustment 6 16 Spi T6963C GLCD HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 407 CHAPTER 6 Libraries mikroC for 8051 T6963C GRAPHIC LCD LIBRARY The mikroC for 8051 provides a library for working with GLCDs based on TOSHI BA 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 reso lution up to 240x128 Because of its low power and small outline it is most suitable for mobile applications such as PDAs MP3 players or mobile measurement 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 Column 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 T6963
88. byte from Port Expander s PORTA char read data Expander Set DITGCLIODnPOrFLA D 0EEP set expander s porta to be input read data Expander Head PorLA GD Expander Read PortB Prototype char Expander Read PortB char ModuleAddress Byte read Description The function reads byte from Port Expander s PortB Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Requires Port Expander must be initialized See Expander Init Port Expander s PortB should be configured as input See Expander Set DirectionPortB and Expander Set DirectionPortAB routines Example Read a byte from Port Expander s PORTB char read data Expander Set DireoctionPortB i0D 0xFP expander s portb to be input read data Expander Read PortB 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 287 CHAPTER 6 Libraries mikroC for 8051 Expander Read PortAB Prototype unsigned int Expander Read PortAB char ModuleAddress Description The function reads word from Port Expander s ports PortA read ings are in the higher byte of the result PortB readings are in the lower byte of the result Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Requires Port Expander must be initialized See Expander Init Port Expander s PortA and PortB should be configured as inputs See Expander Set DirectionPortA Expander Set Direction
89. 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 be initialized for SPI communication see Spi_Glcd_Init routines Example Invert the dot in the upper left corner Gled Dorit 0 217 Spi_Glcd_Line Prototype void SPI Linelint x start int y Start int x end int y Ghar color Description Draws a line on GLCD Parameters x start X coordinate of the line start Valid values 0 127 y start y coordinate of the line start Valid values 0 63 x end X coordinate of the line end Valid values 0 127 y end y coordinate of the line end Valid values 0 63 color color parameter Valid values 0 2 Parameter color determines the line color 0 white 1 black and 2 inverts each dot Requires GLCD needs to be initialized for SPI communication see Spi Init routines Example Draw a line between dots 0 0 and 20 30 Bp Glod 1 30 320 275 360 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi Glcd V Line Prototype void Spi Glcd V Line char y start char y end char pos char color Description Draws a vertical line on GLCD Parameters y start y coordinate of the line start Valid values 0 63 y end y coordinate of the line end Valid values 0 63 x pos X
90. data Ow Read 272 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Ow_Write Description Writes one byte of data via the OneWire bus Parameters par data to be written Requires Devices compliant with the Dallas OneWire protocol Global variable ow Bit must be defined before using this func tion Example Send a byte to the One Wire Bus Ow Write Library Example This example reads the temperature using DS18x20 connected to pin P1 2 After reset MCU obtains temperature from the sensor and prints it on the LCD Make sure to pull up P1 2 line and to turn off the 1 leds dod pinout definition sbit LCD RS at P2 B0 sbit LCD EN at 2 1 sbit LCD D7 at P2 B5 sbit LCD D6 at P2 B4 spit LCD DS at P2 B3 sbit LCD D4 at P2 B2 end icd definition OneWire pinout sbit OW Bit at P1 B2 end OneWire definition Set TEMP RESOLUTION to the corresponding resolution of used DS18x20 sensor ff 188207 9 default setting can be 9 10 11 or 12 18B20 12 const unsigned short TEMP RESOLUTION 9 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 273 CHAPTER 6 Libraries mikroC for 8051 char text 000 0000 unsigned temp void Display Temperature unsigned int temp2write const unsigned short RES SHIFT TEMP RESOLUTION 8 char temp whole unsigned int temp fraction check if tem
91. data from from the current location of GLCD memory and moves to the next location Requires GLCD needs to be initialized see Init routine GLCD side x axis position and page should be set first See functions Gled Set Side Set X and Glcd Set Page Example unsigned short data dots Glod Read Data MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 247 CHAPTER 6 Libraries mikroC for 8051 Glcd Write Data Prototype void Glcd Write Data unsigned short ddata Description Writes one byte to the current location in GLCD memory and moves to the next location Parameters ddata data to be written Requires GLCD needs to be initialized see Init routine GLCD side x axis position and page should be set first See functions Gled Set Side Gled Set X and Gled Set Page Example unsigned short data Ead quite Glcd Fill Prototype void Glcd Fill unsigned short pattern Description Fills GLCD memory with the byte pattern Parameters pattern byte to fill GLCD memory with To clear the GLCD screen use Fill 0 To fill the screen completely use Fill OxFF GLCD needs to be initialized see Gled Init routine Example Clear screen Gled Fill 0 248 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Glcd Dot Prototype void Glcd Dot unsigned short x pos u
92. dati 4 0 ensure that message received flag is 0 5 0 ensure that error flag is 0 ES 1 Enable UART interrupt BI Da Clear UART RX interrupt flag EA 1 Enable interrupts while 1 Endless loop Upon completed valid message receiving Iy datald is set to 255 if dat 5 1 If error detected signal it by Pl OxAA A setting PORT1 to OxAA if dati 4 4 If message received successfully dat 4 05 Clear message received flag j dat 31 Read number of message received bytes for i 1 i lt 3 it4 dat 1 1 Show received data on PORTO dati Ul dati Ol 1 increment received dat 0 Delay ms 10 Rs485slave Send dat 1 And send back to Master 308 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries HW Connection Shielded pair no longer than 300m vcc VCC 58685681 VCC a 6 9 Example of interfacing PC to 8051 MCU via RS485 bus with LTC485 as RS 485 transceiver MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 309 CHAPTER 6 Libraries Message format and CRC calculations Q How is CRC checksum calculated on RS485 master side START BYTE 0x96 10010110 STOP BYTE 0xA9 10101001 PACKAGE START BYTE 0x96 ADDRESS DATALEN DATA1 if exists DATA2 if exists DATA3 if exists CRC STOP BYTE OxA9 DATALEN bits MASTER S
93. dddd dddd CHAPTER 6 mikroC for 8051 Libraries a Description x string with a terminating S char null character Pointer value the X for yord mat is used A 15 written No argu ment is converted The complete conversion spec ification shall be 2 The flags field 15 where a single character is used to justify the output and to print signs and blanks decimal points and octal and hexadecimal prefixes as shown in the following table flags Meaning Left justify the output in the specified field width Prefix the output value with or sign if the out put is a signed type Prefix the output value with a blank if it is a space signed positive value Otherwise no blank 15 pre fixed Prefixes a non zero output value with 0 0x or 0x when used with o x and x field types respectively When used with e f field types the flag forces the output value to include a decimal point The flag is ignored in all other cases Ignore format specifier The width field 15 a non negative number that specifies the mini mum number of printed characters If a number of characters in the output value 15 less than width then blanks are added on the left or right when the flag is specified to pad to the minimum width If width is prefixed with 0 then zeros are padded instead of blanks The width field never truncates a field If a length of the output value exceeds the spec
94. demonstrates how to communicate LCD via the SPI module using serial to parallel convertor MCP23S17 char text mikroElektronika Port Expander module connections sbit SPExpanderRST at P1 B0 sbit SPExpanderCS at 1 1 End Port Expander module connections void main Spi 77 Initialize SPI Spi bed Conrig 0 Initialize LCD over SPI interface Spi Lcd Cmd LCD CLEAR Clear display Spi Led Cmd LCD CURSOR DFE Turn cursor off opi Logd nikroEk Print text LCD column Lod Ohr Append api Logd DubiZ l text ff Print text to LCD 2nd row ist column epi Lod 3 4 Ekron For LCD with more than two rows Spi Lcd Out 4 15 mikroE For LCD with more than two rows MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 375 CHAPTER 6 Libraries mikroC for 8051 HW Connection 1 0 vcc Fo VCC i Y XTAL1 B r1 GND 111 5 ee vec Contrast s Adjustment MCP23S17 79 _ ENS Gc8S681V 3331300711177 6 14 SPI LCD HW connection 376 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries SPI LCD8 8 BIT INTERFACE LIBRARY The mikroC for 8051 provides a library for communication with LCD with HD44780 compliant controllers in 8 bit
95. encompass functions variables symbolic constants user defined data types and labels Each value has an associated name and type also known as a data type The name is used to access the object and can be a simple identifier or complex expression that uniquely refers the object 140 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference Objects and Declarations Declarations establish a necessary mapping between identifiers and objects Each declaration associates an identifier with a data type Associating identifiers with objects requires each identifier to have at least two attributes storage class and type sometimes referred to as data type The mikroC for 8051 compiler deduces these attributes from implicit or explicit declarations in the source code Usually only the type is explicitly specified and the storage class specifier assumes the automatic value auto Generally speaking an identifier cannot be legally used a program before its dec laration point in the source code Legal exceptions to this rule known as forward references are labels calls to undeclared functions and struct or union tags The range of objects that can be declared includes Variables Functions Types Arrays of other types Structure union and enumeration tags Structure members Union members Enumeration constants Statement labels Preproces
96. found at the bottom of this page Parameters data buffer data to be sent datalen number of bytes for transmition Valid values 0 3 protocol that only one device sends data via 485 bus at a time Example char msg 8 send 2 bytes of data to the master RS54858lave Send msg 2 Library Example Requires MCU must be initialized as a Slave for RS 485 communication See RS485slave Init It is the user s responsibility to ensure by This 1s 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 incremented data back to Slave etc Master displays received data on PO while error on receive 0x AA and number of consecutive unsuccessful retries are displayed on P1 Slave displays received data on while error on receive 0xAA is displayed on Hardware configurations in this example are made for the Easy8051B board and AT8988253 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 305 CHAPTER 6 Libraries mikroC for 8051 RS485 Master code char dat 10 Buffer for receving sending messages char i j long count 0 RS485 module connections sbit re405 transceive at 3 2 Transmit Receive control to Poes End RS485 module connections jf dm Interrupt routine vo
97. func expl exp2 exp3 exp4 exp5 also calls func with two arga Semicolon Semicolon is a statement terminator Any legal C expression including the empty expression followed by a semicolon is interpreted as a statement known as an expression statement The expression is evaluated and its value is discarded If the expression statement has no side effects the mikroC for 8051 might ignore it a b Evaluate b but discard value tta Side effect on a but discard value of 3 Empty expression or null statement 138 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference Semicolons are sometimes used to create an empty statement for 1i Ur 1 lt a 3 For more information see the Statements Colon Use colon to indicate the labeled statement start x eke oboe Labels are discussed the Labeled Statements Asterisk Pointer Declaration Asterisk in a variable declaration denotes the creation of a pointer to a type char char ptr a pointer to char is declared Pointers with multiple levels of indirection can be declared by indicating a pertinent number of asterisks Int tint PCI a pointer to an array of integers double double ptr a pointer to a matrix of doubles You can also use asterisk as an operator to either dereference a pointer or as multi plication operator Z
98. if no font is specified then the default 5x8 font supplied with the library will be used Example Write character C on the position 10 inside the page 2 spa Gled Write MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 365 CHAPTER 6 Libraries mikroC for 8051 Spi Glcd Write Text Prototype void SPI Glcd Write Text char text char x pos char page num char color Description Prints text on GLCD Parameters text text to be written x pos text starting position on X axis _ page num the number of the page on which text will be written Valid values 0 7 color color parameter Valid values 0 2 The parameter color determines the color of the text 0 white 1 black and 2 inverts each dot Note For x axis and page layout explanation see schematic at the bottom of this page Requires GLCD needs to be initialized for SPI communication see Spi Init routines Use the Spi_Glcd_Set_Font to specify the font for display if no font is specified then the default 5x8 font supplied with the library will be used Example Write text Hello world on the position 10 inside the page 2 spi Glod Write Text Hello worldl 366 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi Glcd Image Prototype void Spi Glcd Image const code char image Description Displays bitmap on
99. in bytes of any standard or user defined type The mikroC for 8051 standard libraries and your own program and header files must provide unambiguous identifiers or expressions derived from them and types so that the mikroC for 8051 can consistently access interpret and possibly change the bit patterns in memory corresponding to each active object in your program Type Categories A common way to categorize types is to divide them into fundamental derived The fudamental types represent types that cannot be split up into smaller parts They are sometimes referred to as unstructured types The fundamental types are void char int float and double together with short long signed and unsigned variants of some of them For more information on fundamental types refer to the topic Fundamental Types The derived types are also known as structured types and they include pointers to other types arrays of other types function types structures and unions For more information on derived types refer to the topic Derived Types FUNDAMENTAL TYPES The fudamental types represent types that cannot be divided into more basic ele ments and are the model for representing elementary data on machine level The fudamental types are sometimes referred to as unstructured types and are used as elements in creating more complex derived or user defined types The fundamental types include Arithmetic Types Enume
100. in the same sequence as their matching formal parameters Use the function call operator tame expression 1 SApreselon n Each expression the function call is actual argument Number and types of actual arguments should match those of formal function parameters If types do not match implicit type conversions rules will be applied Actual arguments can be of any complexity but order of their evaluation is not specified Upon function call all formal parameters are created as local objects initialized by the values of actual arguments Upon return from a function a temporary object is created in the place of the call and it 1s initialized by the expression of the return statement This means that the function call as an operand complex expression 15 treated as a function result If the function has no result type void or the result is not needed then the function call can be written as a self contained expression In C scalar arguments are always passed to the function by value The function can modify the values of its formal parameters but this has no effect on the actual argu ments in the calling routine A scalar object can be passed by the address if a formal parameter is declared as a pointer The pointed object can be accessed by using the indirection operator 184 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Referen
101. is a multipoint communication which allows multiple devices to be connect ed to a single bus The mikroC for 8051 provides a set of library routines for com fortable work with RS485 system using Master Slave architecture Master and Slave devices interchange packets of information Each of these packets contains synchro nization bytes CRC byte address byte and the data Each Slave has unique address and receives only packets addressed to it The Slave can never initiate communica tion 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 bot tom of this page Library constants START byte value 150 STOP byte value 169 Address 50 15 the broadcast address for all Slaves packets containing address 50 will be received by all Slaves except the Slaves with addresses 150 and 169 External dependencies of RS 485 Library The following vari able must be defined in all projects using RS 485 Library Description Example Control RS 485 extern sbit Transmit Receive sbit Cransceive at rsdo2 Lransceive operation mode MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 301 CHAPTER 6 Libraries mikroC for 8051 Library Routines RS485master Init RS485mas
102. it a comma delimited sequence of values with in braces similar to array For example Referring to declarations from the example above Declare and initialize dots p struct Dor p lay ld G2 S 15 7 0 Declare and initialize circle ol struct Circle o1 1 0 radius is 1 center is at 0 162 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference Incomplete Declarations Incomplete declarations are also known as forward declarations A pointer to a struc ture type A can legally appear in the declaration of another structure B before A has been declared struct A incomplete struct i struct A struct A struct pb The first appearance of A is called incomplete because there is no definition for it at that point An incomplete declaration is allowed here because the definition of B doesn t need the size of A Untagged Structures and Typedefs If the structure tag is omitted an untagged structure is created The untagged struc tures can be used to declare the identifiers in the comma delimited member declarator list to be of the given structure type or derived from it but addi tional objects of this type cannot be declared elsewhere It is possible to create a typedef while declaring a structure with or without tag 4 With Cag typedef struct mystruct M
103. like this This example writes low byte of bit field of myunsigned type to PORTO myunsigned Value For PORTO void main Value For PORTULIO nibble 7 Value For PORTD hi nibble For PORTO typecasting 1 address of structure to pointer to void pointer to void pointer to char 3 dereferencing to obtain the value MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 169 CHAPTER 5 Language Reference mikroC for 8051 TYPES CONVERSIONS The mikroC for 8051 15 a strictly typed language with each operator statement and function demanding appropriately typed operands arguments However we often have to use objects of mismatching types expressions In that case type con version 15 needed Conversion of object of one type means that object s type is changed into another type The mikroC for 8051 defines a set of standard conversions for built in types provided by compiler when necessary For more information refer to the Standard Conversions Conversion is required in the following situations if a statement requires an expression of particular type according to language definition and we use an expression of different type if an operator requires an operand of particular type and we use an operand of different type if a function requires a formal parameter of particular type and we pass it an object
104. ment list of a C function Each comma delimited identifier has the role of a formal argument or placeholder Such macros are called by writing yacro Identirier lt act al arg lisit the subsequent source code syntax is identical to that of a function call indeed many standard library C functions are implemented as macros However there are some important semantic differences The optional actual arg list must contain the same number of comma delimited token sequences known as actual arguments as found in the formal arg _ list of the define line there must be an actual argument for each formal argument An error will be reported if the number of arguments in two lists is not the same A macro call results two sets of replacements First the macro identifier and the parenthesis enclosed arguments are replaced by the token sequence Next any for mal arguments occurring in the token sequence are replaced by the corresponding real arguments appearing in actual arg list Like with simple macro definitions rescanning occurs to detect any embedded macro identifiers eligible for expansion Here is a simple example A simple macro which returns greater of its 2 arguments _ gt B 7 2 B Let s x b c Preprocessor will transform the previous line into x a b gt a b c d
105. 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 initialize 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 External dependencies are the same as Port Expander Library external dependen cies Library Routines Spi Led8 Config Spi Out Spi Led8 Out Spi Led8 Chr Spi Led8 Chr Spi Led8 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 377 CHAPTER 6 Libraries mikroC for 8051 Spi Lcd8 Config Prototype void Spi Lcd8 Config char DeviceAddress Description Initializes the LCD module via SPI interface Parameters DeviceAddress spi expander hardware address see schematic at the bottom of this page Requires SPExpandercs and SPExpanderRsT variables must be defined before using this function The SPI module needs to be initialized See Spi_Init and Spi Init Advanced routines Example port expander pinout definition sbit SPExpanderRST at P1 B0 sbit SPExpanderCS at 1 1 Init 44 initialize spi interface opi Leds Contig 0 intialize lcd i
106. 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 r read signal pin on GLCD control port c command data signal pin on GLCD control port rst reset signal pin on GLCD control port Display RAM organization The i cuts RAM into panels a complete panel is one graph ics panel followed by a text panel see schematic below schematic GRAPHICS PANEL 0 PANEL TEXT PANEL 0 GRAPHICS PANEL 1 PANEL 1 TEXT PANEL 2 SPExpanderCs and SPExpanderRsT variables must be defined before using this function The SPI module needs to be initialized See the Spi Init and Spi Init Advanced routines port expander pinout definition sbit SPExpanderRST at PI B0 PI BIl Spi Init MASTER OSC DIV4 IDLE LOW IDLE 2 ACTIVE DATA ORDER MSB epi T6963C Config 24U 64 B 0 CHAPTER 6 mikroC for 8051 Libraries Spi T6963C WriteData Prototype void Spi T6963C WriteData unsigned char Ddata Description Writes data to T6963C controller via SPI interface Parameters Ddata data to be written Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine opi TOPSSGL WriteDatalAOdEL Spi T6963C WriteCommand Prototype void Spi T6963C WriteCommand unsigned char Dda
107. of the upper left box corner 1 X coordinate of the lower right box corner y1 y coordinate of the lower right box corner pcolor color parameter Valid values T6963C BLACK and T6963C WHITE Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Example 16963 Box 0 119 239 127 T6963C WHITE T6963C Circle Prototype void 6963 Circle int x int y long unsigned char pcolor Description Draws a circle on GLCD Parameters x X coordinate of the circle center y y coordinate of the circle center radius size pcolor color parameter Valid values T6963C BLACK and T6963C WHITE Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Example TOO C 1470 Gap 210 299920 Wate MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 417 CHAPTER 6 Libraries mikroC for 8051 T6963C_Image Prototype void T6963C Image const code char pic Description Displays bitmap on GLCD Parameters pic image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroC for 8051 pointer to const and pointer to RAM equivalency Use the mikroC s integrated GLCD Bitmap Editor menu option Tools GLCD Bitmap Editor to convert image to a constant array suitable for displaying on GLCD Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine
108. pointers The internal arithmetic performed on pointers depends on the memory model in force and the presence of any overriding pointer modifiers When performing arith metic with pointers it is assumed that the pointer points to an array of objects Arrays and Pointers Arrays and pointers are not completely independent types in the mikroC for 8051 When the name of an array comes up in expression evaluation except with opera tors 5 and sizeof it is implicitly converted to the pointer pointing to array s first element Due to this fact arrays are not modifiable lvalues Brackets 1 indicate array subscripts The expression id exp is defined as d exp where either id 15 a pointer and exp 15 an integer or idis an integer and exp is a pointer The following statements are true 1 1 1 al 1 According to these guidelines it can be written 158 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference 4 pa points to 4 x pa 3 x a 7 DuC y 2 y a 4 3 Also the care should be taken when using operator precedence Equal to pat increments the pointer Increments the pointed object The following examples are also valid but better avoid this syntax as it can make the code really illegible m e sam
109. possible type in every situation It applies to all programming in general and doubly so with microcontrollers Types efficiency 1s determined by the part of RAM memory that is used to store a variable constant See the example 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 func tion 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 vari ables Note 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 using 112 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 4 mikroC for 8051 8051 Specifics 8051 MEMORY ORGANIZATION The 8051 microcontroller s memory is divided into Program Memory and Data Memory Program Memory ROM is used for permanent saving program being executed while Data Memory RAM 15 used for temporarily storing and keeping intermediate results and variables Program Memory ROM Program Memory ROM is used for permanent saving program CODE being exe cuted The memory is read only Depending on the settings made in compiler pro gram memory may also used to store a constant variables The 8051 executes pro grams stored in program memory on
110. rather a new name for a given type In other words the typedef declaration is identical to a normal declaration but instead of objects it declares types It is a common practice to name custom type identifiers with start ing capital letter this is not required by the mikroC for 8051 For example Let s declare a synonym for unsigned long int typedef unsigned long int Distance Now synonym Distance can be used as type identifier Distance i declare variable i of unsigned long int 178 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference In the typedef declaration as in any other declaration several types can be declared at once For example typedef int Pti Array 10 Pt i is a synonym for type pointer to int and Array is a synonym for type array of 10 int elements ASM DECLARATION The mikroC for 8051 allows embedding assembly in the source code by means of the asm declaration The declarations asm and asm are also allowed in the mikroC for 8051 and have the same meaning Note that numerals cannnot be used as absolute addresses for SFR or GPR variables in assembly instructions Symbolic names may be used instead listing will display these names as well as addresses Assembly instructions can be grouped by the asm keyword or asm or asm asm block of assembly instructions There are two ways to embeding
111. read write pointers in auto increment mode receive filters set to default CRC MAC Unicast MAC Broadcast in OR mode flow control with TX and RX pause frames in full duplex mode frames are padded to 60 bytes CRC maximum packet size 15 set to 1518 Back to Back Inter Packet Gap 0x15 in full duplex mode 0x12 in half duplex mode Non Back to Back Inter Packet Gap 0x0012 in full duplex mode 0x0c12 in half duplex mode Collision window is set to 63 in half duplex mode to accomo date 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 Parameters RAM buffer containing valid MAC address ip RAM buffer containing valid IP address fullDuplex ethernet duplex mode switch Valid values 0 half duplex mode and 1 full duplex mode 336 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries ae appropriate hardware SPI module must be previously initial ized Example define Spi Ethernet HALFDUPLEX 0 define Spi Ethernet FULLDUPLEX 1 unsigned char myMacAddr 6 0x00 0x14 OxA5 0x76 0 19 Ox3f my MAC address unsigned char myIpAddr 192 168 IP addr epi Init Brhernet IDILisPORTO U SPORTO 1 myMacAQor myIpAddr Spi Ethernet FULLDUPLEX Spi Eth
112. recursion is not supported because of no easily usable stack and limited memory 8051 Specific C Language Exstensions mikroC for 8051 has additional set of keywords that do not belong to the ANSI stan dard C language keywords code data bdata xdata small gomp pac large ANTE epit hit ilevel Related topics Keywords 8051 Specific 98 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroC for 8051 Specifics PREDEFINED GLOBALS AND CONSTANTS To facilitate programming of 8051 compliant MCUs the mikroC for 8051 imple ments a number of predefined globals and constants All 8051 SFR registers are implicitly declared as global variables of volatile unsigned int These identifiers have an external linkage and are visible in the entire project When creating a project the mikroC for 8051 will include an appropriate c file from defs folder containing declarations of available SFR registers and constants PO 1 For a complete set of predefined globals and constants look for Defs in the mikroC for 8051 installation folder or probe the Code Assistant for specific letters Ctrl Space in the Code Editor ACCESSING INDIVIDUAL BITS The mikroC for 8051 allows you to access individual bits of 8 bit variables It also supports sbit and bit data types Accessing Individual Bits Of Variables Simply use the direct member
113. routine code is generated in the place of the call so the call doesn t count against the nested call limit Requires Arguments must be variable of scalar type 1 e Arithmetic Types and Pointers Example OxlAC3O0F4 tmp Highest d Equals 0x01 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 105 CHAPTER 3 Specifics mikroC for 8051 Delay_us Prototype void Delay us const unsigned long time in us Description Creates a software delay in duration of time in us microseconds a constant Range of applicable constants depends on the oscillator frequency 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 Delay us 1000 One millisecond pause Delay ms Prototype void Delay ms const unsigned long time in us Description Creates a software delay in duration of time in ms microseconds a constant Range of applicable constants depends on the oscillator frequency 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 Delay ms 1000 One millisecond pause 106 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 Vdelay_ms Prototype Returns Description Requires Example Delay_Cyc Prototype Returns Description Requires Example CHAPTER 3 Specifics
114. selector with a variable followed by one of iden tifiers FO F1 F15 With F15 being the most significant bit There is no need of any special declarations This kind of selective access is an intrinsic feature of mikroC for 8051 and can be used anywhere in the code Identifiers 0 15 are not case sensitive and have a specific namespace You may override them with your own members 0 15 within any given structure If you are familiar with a particular MCU you can also access bits by name Clear TRISBS3 TRISBGItS TRISB3 D See Predefined Globals and Constants for more information on register bit names Note If aiming at portability avoid this style of accessing individual bits use the bit fields instead MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 99 CHAPTER 3 Specifics mikroC for 8051 sbit type The mikroC Compiler have sbit data type which provides access to bit addressable SFRs For example sbit LEDA at sbit name at sfr name Bbit position The previously declared SFR sfr name is the base address for the sbit It must be evenly divisible by 8 The bit position which must be a number from 0 7 follows the dot symbol 7 7 and specifies the bit position to access For example sbit OV PSW B2 sbit CY PSW B7 bit type The mikroC Compiler provides a bit data type that may be used for variable decla rations It can not be used for argument lists
115. similar to 0 1 n exactly n times greedy n at least n times greedy n m at least n but not more than m times greedy zero or more non greedy similar to 0 one or more non greedy similar to 1 zero or one non greedy similar to 0 1 n exactly n times non greedy n at least n times non greedy n m at least n but not more than m times non greedy So digits in curly brackets of the form n m specify the minimum number of times to match the item n and the maximum m The form n is equivalent to n n and matches exactly n times The form n matches n or more times There is no limit to the size of n or m but large numbers will chew up more memory and slow down execution If a curly bracket occurs in any other context it 15 treated as a regular character 72 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Examples count r 8 matches strings like counter countelkjdflkj9r and countr count r matches strings like counter countelkjdflkj9r but not countr count r matches strings like oobar foobbr and foobr but not foobalkj9r counte 2 r matches string counteer counte 2 r matches strings like counteer counteeer counteeer e c counte 2 3 r matches strings like counteer or counteeer but not counteeeer A little explanati
116. slave Parameters ack acknowledge signal parameter If the ack 0 not acknowledge signal will be sent after reading otherwise the acknowledge signal will be sent Requires Soft PC must be configured before using this function See Soft I2C Init routine Also START signal needs to be issued in order to use this func tion See Soft I2C Start routine Example unsigned short take nd gata send the acknowlecge signal Lake IZC Read 0 7 312 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Soft_I2C Write Prototype unsigned short Soft I2C Write unsigned short Data Returns 0 If there were no errors 1 1f write collision was detected on the PC bus Description Sends data byte via the PC bus Parameters Data data to be sent Requires Soft must be configured before using this function See Soft I2C Init routine Also START signal needs to be issued in order to use this func tion See Soft I2C Start routine Example unsigned short data error Brror Sort Write data error Soft Nes Write Soft_I2C Stop Issues STOP signal Requires Soft must be configured before using this function See Soft I2C Init routine Example Issue STOP signal Soft I2C Stop MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 315 CHAPTER 6 Libraries mikroC for 8
117. to float 2 Otherwise if either operand is unsigned long the other operand is converted tO unsigned long MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 171 CHAPTER 5 Language Reference mikroC for 8051 3 Otherwise if either operand is long then the other operand is converted to long 4 Otherwise if either operand is unsigned then the other operand is converted to unsigned 5 Otherwise both operands are int The result of the expression is the same type as that of the two operands Here are several examples of implicit conversion 2 3 1 y 2 2 3 1 5 4 5 7 4 3 ge F gt 24S 2 2 93 P Ja FF do X f al gy F T 15 74 222074 D 32 75 Ty Pointer Conversions Pointer types can be converted to other pointer types using the typecasting mecha nism char str ant str char More generally the cast type will convert a pointer to type pointer to EXPLICIT TYPES CONVERSIONS TYPECASTING In most situations compiler will provide an automatic implicit conversion of types where needed without any user s interference Also the user can explicitly convert an operand to another type using the prefix unary typecast operator type object This will convert object to a specified t ype Parentheses are mandatory For example Let s have two variables of char type char a b Following line will coe
118. value to be used CAN TX XTD FRAME 6 with CANSPIWrite CAN TX NO RTR FRAME Can Init Flags CAN CONFIG SAMPLE THRICE amp Form value to be used CAN CONFIG PHSEG2 PRG ON amp with CANSPIInit CAN CONFIG XTD MSG amp CAN CONFIG DBL BUFFER ON amp CAN CONFIG VALID XTD MSG amp CAN CONFIG LINE FILTER OFF Spr Inet Initialize SPI module CANSPIIDnILIAILISONN 2 2 2 1 U02am Flags Initialize CAN SPI module CANSPISetOperationMode CAN MODE CONFIG OxFF Set CONFIGURATION mode CANSPISetMask CAN MASK 1 1 CONFIG XTD MSG f Bet all maski bite te ones CANSPISetMask CAN MASK B2 1 CAN CONFIG XTD MSG 77 Set all mask bits to ones CANSPISeTtEIITer AN FILTER Be ES 12111 CAN CONFIG XTD 7 id of filter BJ to 12112 CANSPISetOperationMode CAN MODE NORMAL OxFF NORMAL mode Tx 3 Set tx ID 238 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries while 1 Endless loop Msg Revd CANSPIRead amp Rx ID y RxTx Data amp Rx Data Len amp Can Rev Flags Receive message if Rx ID 12111u Msg Revd If message received check id PO RxIx Data 0 ID correct output data at PORTO BETXx Datal 2 Increment received data CANSPIWrite Tx ID Dara 1 Can send Flags Send incremented data back Eat ed HW Connection n 100K VCC CF EN
119. x on control port if bit x in bit mask is set to 1 Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Example clear bits 0 and 1 on control port DLSSREBILIOUEDS MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 419 CHAPTER 6 Libraries mikroC for 8051 T6963C_SetBit Description Sets control port bit s Parameters b bit mask The function will set bit on control port if bit in bit mask 15 set to 1 Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Example set bits 0 and 1 on control port TOIDU T6963C_NegBit Prototype void 6963 NegBit char b Description Negates control port bit s Parameters b bit mask The function will negate bit x on control port if bit in bit mask is set to 1 Requires Toshiba GLCD module needs to be initialized See the T6963C_ Init routine Example negate bits 0 and 1 on control port T69630 NegBit 0x03 420 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries T6963C DisplayGrPanel Prototype void T6963C DisplayGrPanel char n Description Display selected graphic panel Parameters graphic panel number Valid values 0 and 1 Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Example display graphic panel 1 T695
120. 051 Library Example The example demonstrates Software Library routines usage The 8051 MCU 15 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 char seconds minutes hours day month Global date time variables year 44 Software IZC connections sbit SOIL at 1 3 sbit Soft I2C Sda at P1 B4 End Software I2C connections LCD module connections sbit LCD RS at P2 B0 sbit LCD EN at 2 1 sbit LCD D7 at P2 B5 sbit LCD D6 at P2 B4 sbit LCD D5 at PZ2 B35 sbit LCD D4 at P2 B2 End LCD module connections Reads time and date information from RTC PCFB583 void Read Time GOLL Start SOLL Write OxA0 7 Issue start signal Address PCF8583 see PCF8583 datasheet Start from address 2 Issue repeated start signal Address PCF8583 for reading R W 1 onLt 140 Wrive z 3 Beare SOTE WEItGelOxAL J seconde Sort Beadil minutes e Sort 1202 Beadtl j hours e Sort Reaad 1 day Sort 120 1 month e Sort Read 0 SUL Read seconds byte Read minutes byte Read hours byte Read year day byte Read weekday month byte Issue stop signal FIL temo ee Formats date and time void Transform Time seconds aeBconds amp OxP gt gt 4 10 seconds amp xD E
121. 1 0 curs 0 Cposx cposy 0 Text messages zd TO6SBOL write U 0 ROM MODE XOR T5963C write text txtl 0 15 Spi TOJ03C ROM MODE XOR DODIOSOI d Spi T6963C cursor height 8 8 pixel height Spi cursor U U Move cursor Jere Spi T6853C cursor 0 J Cursor off Draw rectangles ci 753630 rectangle 696820 rectangle opi rectangle Spi T6903 rectangle 0 0 239 127 Spi 16963 WHITE 20 20 219 107 Spi T6963C WHITE 40 40 199 87 Spi T6963C WHITE 60 60 179 67 Spi T6963C WHITE n Draw a cross d 63630 Line Uy D 22 127 Spi TOB53SL WHITE 3 T636230 line U 127 229 1 Opa TBSOSC WHITE 3 Draw solid boxes Spi TesesC box 0 0 233 B T59563C WHITE j TOIA 115 239 127 WHITE 2 Draw circles T6903C circle l2D 64 10 Spi 1539620 Walls T6S6s0 Circle 120 64 30 Spi Te sos WHITE 769632 circle 120 64 50 Spi 5963 WHITE T6S623L carcle i20 64 79 T69803C WHITE T6963C circle l120 54 90 7659630 WHITE T695630 carcle i2G B4 110 Tb9603C WHITE 7 opi 76963 circle l12D 64 130 Spi T6963C WHITE 7 404 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED
122. 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 Anew tab will be opened This is a new source file Select File Save from the drop down menu or press Ctrl S or click the Save File Icon fH from the File Toolbar and name it as you want 92 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment If you use the New Project Wizard an empty source file named after the project with extension c will be created automatically The mikroC 8051 does not require you to have a source file named the same as the project it s just a matter of conven Opening an existing file 1 Select File Open from the drop down menu or press Ctrl O or click the Open File Icon from the File Toolbar In Open Dialog browse to the location of the file that you want to open select it and click the Open button 2 The selected file is displayed in its own tab If the selected file is already open its current Editor tab will become active Printing an open file 1 Make sure that the window containing the file that you want to print is the active window 2 Select File gt Print from the drop down menu or press Ctrl P 3 In the Print Preview Window set a desired layout of the document and click the OK button The file will be printed on the selected printer Saving file 1 Make sure that t
123. 112114 3 dimensional array of size J3x2x4 void func int n L2 4 we can omit first dimension n 2 3 increment the last element void main func a pzfel You can initialize a multi dimensional array with an appropriate set of values with in braces For example int al 3 2 1 2 2 6 3 7 POINTERS Pointers are special objects for holding or pointing to memory addresses In the mikroC for 8051 address of an object in memory can be obtained by means of an unary operator amp To reach the pointed object we use an indirection operator on a pointer A pointer of type pointer to object of type holds the address of that is points to an object of type Since pointers are objects you can have a pointer pointing to a pointer and so on Other objects commonly pointed to include arrays structures and unions A pointer to a function is best thought of as an address usually a code segment where that function s executable code 15 stored that 1s the address to which control is transferred when that function 15 called Although pointers contain numbers with most of the characteristics of unsigned inte gers they have their own rules and restrictions for declarations assignments con versions and arithmetic The examples in the next few sections illustrate these rules and restrictions Pointer Declarations Pointers are declared the same as any other v
124. 3C DisplayGrPanelil T6963C DisplayTxtPanel Prototype void 6963 DisplayTxtPanel char n Description Display selected text panel Parameters graphic panel number Valid values 0 and 1 Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Example display text panel 1 Teves DisplayTxtPanelil MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 421 CHAPTER 6 Libraries mikroC for 8051 T6963C SetGrPanel Prototype Description Compute start address for selected graphic panel and set eee ate internal pointers All graphic operations wi preformed at this graphic pane be Parameters graphic panel number Valid values 0 and 1 Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Example set graphic panel 1 as current graphic panel 11277 T6963C SetTxtPanel Prototype void T6963C SetTxtPanel char n Description Compute start address for selected text panel and set appropriate internal pointers All subsequent text operations will be preformed at this text panel Parameters n text panel number Valid values 0 and 1 Requires 2 GLCD module needs to be initialized See the 6963 Init routine Example set text panel 1 as current text panel 173 422 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR E
125. 4 Example char txt 15 PloatIoSGErirlrl Ext 7 Ext 372 2 PlostTGoStrifr2 f cxt is 122 4507 Cerise 77 Eee is 458 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Dec2Bcd Prototype unsigned short Dec2Bcd unsigned short decnum Converted BCD value Description Converts input unsigned short integer number to its appropriate BCD representation Parameters decnum unsigned short integer number to be converted Example unsigned short a b 22 Dec2Bcd a b eguals 34 Bcd2Dec16 Prototype unsigned 2 16 unsigned bcdnum Converted decimal value Description Converts 16 bit BCD numeral to its decimal equivalent Parameters pcdnum 16 bit BCD numeral to be converted Example unsigned a b 0x1234 a equals 4660 Bcd2Dec16 a b equals 1234 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 459 CHAPTER 6 Libraries mikroC for 8051 Dec2Bcd16 Prototype unsigned Dec2Bcdl6 unsigned decnum Returns Converted BCD value Description Converts unsigned 16 bit decimal value to its BCD equivalent Parameters decnum unsigned 16 bit decimal number to be converted Example unsigned b 234052 Dec2Bcd16 a b equals 9029 460 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED W
126. 51 Examples Led Blinking LedBlinking me proj Globals TypeDef Tage Includes Routine List lg Enter routine name to filer the ti Delay m unsigned long m Project LedBiriing mcpeoy complated 312 ma Finished successfully 19 mar 2008 13 09 22 5 Led mi The Code Editor features adjustable Syntax Highlighting Code Folding Code Assistant Parameters Assistant 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 36 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment The source level Software Simulator lets you debug executable logic step by step by watching the program flow The New Project Wizard is a fast reliable and easy way to create a project Help files are syntax and context sensitive Like in any modern Windows application you may customize the layout of mikroC for 8051 to suit your needs best Spell checker underlines identifi
127. 56 AW COUMCCHON ET 258 Keypad gt sirens oe oe Oe eae 259 External dependencies of Keypad 259 LiDfaly ROUUNCS spin d ag dr Var dado Peas c 259 Keypad 259 Keypad Key PTeSS 259 Keypad Key Click 259 Keypad_lnit 259 Keypad 260 _ _ 260 Library 261 FV CONNECCION 22220 riser iur 4 qs odi 263 Regio odors wan bers 264 External dependencies of LCD Library 264 xvi MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 Table of Contents Library 264 GG WAM RT 265 D IRR 265 OU 266 CE vane toad oe oR he Chea e Eee 266 267 Lcd 267 Available LCD Commands
128. 9 126 Token Extraction Example 126 Gori i gea e cated ede ee we GS Ge a oe 127 Integer 127 Long and Unsigned Suffixes 127 DEGCINAl Pcr 128 MP 128 BINA gaan park ae ee es ae woe 129 129 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Table of Contents mikroC for 8051 Floating Point Constants 129 Character Constants 130 Escape Sequences 130 DISAIMIDIQUAUON 23 th d p m mes 12 459 d Ee 131 GONSIAINS os 2e Snedecor we dads 132 Line Continuation with Backslash 132 Enumeration Constants 133 Pointer Constants 133 Constant Expressions 134 eee bd 135 Dr 136 Case Sensitivity 136 Uniqueness an
129. 963C NegBit Description Negates control port bit s Parameters b bit mask The function will negate bit x on control port if bit x in bit mask is set to 1 Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example negate bits 0 and 1 on control port TOSO3L Negeit 0x03 396 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi T6963C DisplayGrPanel Prototype void Spi T6963C DisplayGrPanel char n Description Display selected graphic panel Parameters n graphic panel number Valid values 0 and 1 Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example display graphic panel 1 7979632 DisplayorPanei 11 Spi T6963C DisplayTxtPanel Prototype void Spi T6963C DisplayTxtPanel char n Description Display selected text panel Parameters n text panel number Valid values 0 and 1 Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example display text panel 1 69020 DisSplayIxtPaneltl SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 397 CHAPTER 6 Libraries mikroC for 8051 Spi T6963C SetGrPanel Prototype void Spi T6963C SetGrPanel char n Compute start address for selected graphic panel and set d ropri ate internal pointers All pe gr
130. A SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Regular expressions By checking this box you will be able to advance your search through Regular expressions Find Text Search for A Cancel Related topics Keyboard shortcuts Edit Toolbar Advanced Edit Toolbar MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 19 CHAPTER 2 Environment mikroC for 8051 VIEW MENU OPTIONS Toolbars k Debug Windows Routines List Project Settings Code Explorer Project Manager 11 Library Manager Bookmarks Messages Macro Editor Windows Project Manager Shift Ctrl F11 Show Hide Project Manager window 20 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment TOOLBARS File Toolbar File Toolbar 15 a standard toolbar with following options Edit Toolbar Edit Toolbar is a standard toolbar with following options Undo last change Redo last change MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 21 CHAPTER 2 Environment mikroC for 8051 gt Cut selected text to clipboard Copy selected text to clipboard Paste text from clipboard Advanced Edit Toolbar Comment selected code or put single line comment if there is no selec 3 tion Uncomment selected code or remove single line comment if there is no dia selection Se
131. AN FILTER Be PF4 3 CAN CONFIG XTD MSG Set id of filter B2 F4 to 3 CANSPISetOperationMode CAN MODE NORMAL OxFF Set NORMAL mode RxTx Datal 0 9 initial data to be sent ID 12111 y Set transmit ID CANSPIWrILe T ID BXIx Data 1 Send Flags Send initial message while 1 Endless loop Msg Revd CANSPIRead amp Rx ID RxTx Data amp Rx Data Len Rev Flags 27 Receive message L Rx ID 30 Msg Rovd 1 If message received check id RXTx 0 ID correct output data at PORTO r Increment received data Delay me 10 CANSPINPITte IX ID Bale 1 Send Flags Send incremented data back Code for the second CANSPI node unsigned char Can Init Flags Can Send Flags Flags CAN flags unsigned char Rx Data Len Received data length in bytes char RxTx Data 8 CAN rx tx data buffer char Msg Reception flag long Tx ID Rx ID CAN rx and tx ID MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 237 CHAPTER 6 Libraries mikroC for 8051 CANSPI module connections Canspi cS at PI BO shit DancpLl Pl B3j End CANSPI module connections void main Lan 0 Can send Flags D Clear flags Can Roy Flags 0 Send Flags CAN TX PRIORITY U Form
132. APTER 5 mikroC for 8051 Language Reference 1 Both expressions have to be of arithmetic type expression2 and expression3 are subject to usual arithmetic conversions which determines the resulting type 2 Both expressions have to be of compatible struct or union types The resulting type 15 a structure or union type of expression2 and expression3 Both expressions have to be of void type The resulting type 15 void Both expressions have to be of type pointer to qualified or unqualified versionsof compatible types The resulting type is a pointer to a type qualified with all type qualifiers of the types pointed to by both expressions One expression 15 a pointer and the other is a null pointer constant The resulting type is a pointer to a type qualified with all type qualifiers of the types pointed to by both expressions One expression 15 a pointer to an object or incomplete type and the other is a pointer to a qualified or unqualified version of void The resulting type is that of the non pointer to void expression J 92 ON ASSIGNMENT OPERATORS Unlike many other programming languages C treats value assignment as operation represented by an operator rather than instruction Simple Assignment Operator For a common value assignment a simple assignment operator is used expressionl expression2 The expressioni 1s an object memory location to which the value of expres sion2 is assigned Operand expr
133. BEDDED WORLD mikroC for 8051 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 473 c mm oou Rete 0101010 OO OO 00 00 por Om UJO2 90JXIUJ3921JJO 5 12e1u02 jesodoid e 1 uonsenb 1 1 Aue o e e e 181919 0 AYAV YAU LYOddNS 1V2INH23L MOU SN ja jeuonippe snf no 10 sjonpoud ano Aue Swajqoid Gui ueuasdxe JI ege Tee SNOILA TOS dH VMCHVH 3d VMLJOS U41001149130 9 Mouser Electronics Authorized Distributor Click to View Pricing Inventory Delivery amp Lifecycle Information mikroElektronika MIKROE 408 MIKROE 730
134. C Box T6963C Circle T6963C Image T6963C Sprite T6963C Set Cursor Note The following low level library routines are implemented as macros These macros can be found in the 76963c n header file which is located in the T6963C example projects folders T6963C ClearBit T6963C SetBit T6963C NegBit T6963C DisplayGrPanel T6963C DisplayTxtPanel T6963C SetGrPanel T6963C SetTxtPanel T6963C PanelFill T6963C GrFill T6963C TxtFill T6963C Cursor Height T6963C Graphics T6963C Text T6963C Cursor T6963C Cursor Blink 410 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 T6963C_Init CHAPTER 6 Libraries Prototype void 6963 Init unsigned int width unsigned char height unsigned char fntW Description Initalizes the Graphic Lcd controller Parameters width width of the GLCD panel height height of the GLCD panel fntw 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 GRAPHICS PANEL 0 PANEL 0 TEXT PANEL 0 GRAPHICS PANEL 1 PANEL 1 TEXT PANEL 2 Requires Global variables T6963C dataPort Data Port T6963C ctrlPort Control Port T6963C ctrlwr write signal pin T6963C ctrird read signal pin T6963C_ctrlcd command data signal pin T6963C ctrlrst reset signal pin must be defin
135. D6 at P2 B4 spit LCD DS at P2 B3 sbit LCD D4 at P2 B2 end lod definitions void main cnt 0 Reset counter Keypad Init Initialize Keypad Led Initialize LOD Lcd LCD CLEAR Clear display Lcd Cmd LCD CURSOR OFF Off Log OULIL 1 Write message text LCD LEO DuLIZ 1 Tamees kp 0 Reset key code variable Wait for key to be pressed and released do kp Keypad Key Click Store key code in kp variable while kp Prepare value for output transform key to it s ASCII value switch kp MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 261 CHAPTER 6 Libraries mikroC for 8051 10 kp 42 break Uncomment this block for keypad4x3 case 11 kp 48 break 0 case 12 kp 35 break default kp 48 case 1 kp 49 Uncomment this case 2 kp 50 case 3 kp 51 case 4 kp 65 case 5 kp 52 case 6 kp 53 case 7 kp 54 case 8 kp 66 case 9 kp 55 case 10 kp 56 case 11 kp 5 7 case 12 kp 67 case 13 kp 42 case 14 kp 48 case 15 kp 35 case 16 kp 68 1 kp oldstate cnt 1 oldstate kp else Lcd Chr 1 10 kp if cnt 255 cnt 0 Led 10 WordTOSLtricOont txt Lod DuLiZ 10 while 1 d break biock for br
136. DWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi_T6963C_Dot Prototype void iw T6963C Dot int x int y unsigned char color Description Draws a dot in the current graphic panel of GLCD at coordinates x y Parameters x dot position on x axis y dot position on y axis color color parameter Valid values Spi T6963C BLACK spi T6963C WHITE Example TBSESC DoL xU yo poolor Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 389 CHAPTER 6 Libraries mikroC for 8051 Spi_T6963C_Write_Char Prototype void Spi 6963 Write Char unsigned char 277 char x unsigned char y unsigned char mode Description Writes a char in the current text panel of GLCD at coordinates x y Parameters c char to be written x char position on x axis y char position on y axis node mode parameter Valid values Spi_T6963C_ ROM MODE OR Spi 6963 ROM MODE Spi_T6963C_ROM_ MODE AND and V Spi T6963C ROM MODE TEXT Mode parameter explanation OR Mode In the OR Mode text and graphics can be displayed and the data 1s 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 E data are com bined via the logical exclusive This
137. E transition ofr the clock SPI clock polarity 3 Clock idle level is low CLK IDLE LOW Clock idle level is high CLK IDLE HIGH Data order 5 Most significant bit sent first DATA ORDER MSB Least significant bit sent first DATA ORDER LSB MCU must have SPI module Example Set SPI to the Master Mode clock Fosc 4 clock IDLE state low and data transmitted at low to high clock edge Spi Init Advanced MASTER OSC DIV4 DATA ORDER MSB CLK IDLE LOW IDLE 2 ACTIVE MASTER OSC DIV64 MASTER OSC DIV128 330 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi Read Prototype unsigned short Spi Read unsigned short buffer Received data Description Reads one byte from the SPI bus Parameters buffer dummy data for clock generation see device Datasheet for SPI modules implementation details Requires SPI module must be initialized before using this function See Spi Init and Spi Init Advanced routines Example read a byte from the SPI bus unsigned short take dummyl take Spi Beadidummpl Spi Write Prototype void Spi Write unsigned short wrdata Description Writes byte via the SPI bus Parameters wrdata data to be sent Requires SPI module must be initialized before using this function See Spi Init and Spi Init Advanced routines Example write a byte to the SPI bus unsigned short buffer writeipur
138. E AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Max7219 anit Initialize max7219 while 1 Endless loop for digit value 0 digit values 9 digit valued 4 Lor digit posiltLlone0 digit digit DOSIEIOR 4 maxi Select max7219 opi position Send digit position Spi Write digit value 44 Send digit value Deselect Deselect max7219 Delay ms 300 HW Connection VCC DIS7 0156 0155 DIS4 an DIS3 0152 DIS1 DISO AOM ON o VCC gt f 7 N 6 11 SPI HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 333 CHAPTER 6 Libraries mikroC for 8051 SPI ETHERNET LIBRARY The ENC28J60 is a stand alone Ethernet controller with an industry standard Serial Peripheral Interface SPI It is designed to serve as an Ethernet network interface for any controller equipped with SPI The ENC28J60 meets all of the IEEE 802 3 specifications It incorporates a number of packet filtering schemes to limit incoming packets It also provides an internal DMA module for fast data throughput and hardware assisted IP checksum calcula tions Communication with the host controller is implemented via two interrupt pins and the SPI with data rates of up to 10 Mb s Two dedicated pins are used for LED link and network activity indication This library is design
139. E AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 Table of Contents Program Memory 113 Internal Data Memory 114 External Data 115 SFR MOMON reisa kaiia ai e ne ee 115 Memory x 9 3 9 3 3 sierde 9 373 93 CAE wi Re arae oe eM ed ale edd 116 116 Compact model PoE 116 Large model ee dedi oic 117 Memory Type Specifiers 117 ess bee oe E E ee See ewes ee sees sere 118 onc 118 coq 118 ocu wm 119 119 120 5 mikroC Language 122 Lexical Elements Overview 122 Whitespace cade coe ooh eed So exe Phe owt eed PE qan 123 Whitespace in Strings 123 Line Splicing with Backslash 124 COMMNGHIS ed ee ee Hoe yes eae 124 bode 124 Cr COMMONS eqs adu Fargo Sd 125 Nested comments 125 TOKO uix u ww eroc rs24939 999257299 992293459599 9952224999 999
140. E SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment RUN MENU OPTIONS Start Debugger Stop Debugger Pause Debugger Step Into step Over Step Out M Jump To Interrupt Toggle Breakpoint F5 Breakpoints Shift4F4 Clear Breakpoints Shift Ctrl F5 Watch Window Shift F5 View Stopwatch Disassembly mode eee MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 29 CHAPTER 2 Environment mikroC for 8051 Show Hide Breakpoints Shift F4 Breakpoints B ClearBreakpoints Shift Ctrl4F5 Clear Breakpoints Gd Watch Window 5 Show Hide Watch Window Show Hide Stopwatch Window Toggle between C source and Disassembly mode i disassembly Related topics Keyboard shortcuts Debug Toolbar TOOLS MENU OPTIONS mE Programmer 4 USART Terminal EEPROM Editor Asai Chart Seven Segment Convertor Export Code To HTML LCD Custom Character GLCD Bitmap Editor UDP Terminal af Options 30 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Generate HTML code suitable for publishing ote eee le source code on the web Generate your own custom LCD characters Generate bitmap pictures for GLCD Related topics Keyboard shortcuts Tools Toolbar HELP MENU OPTIONS Help Check For Updates mikraElekkronika Support Forums mikraElekkronika Web Page How To Register
141. E3MikroElektronika SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD waking it sigle mikroC for 8091 juu ad snm writ 11 222 9 9409 40 4 efe o o o o o o o woo o o o oe eo Develop your applications quickly and easily with the world s most intuitive mikroC for 8051 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 mikroC for 8051 makes a fast and reliable tool which can satisfy needs of experienced engineers and beginners alike mikroC for 8051 DISCLAIMER mikroC for 8051 and this manual are owned by mikroElektronika and are protected 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 with out the written consent from the mikroEelktronika 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 prohibit ed HIGH RISK ACTIVITIES The mikroC for 8051 compiler is not fault tolerant and is not designed manufactured or intended for use or resale as on line control equipment in hazardous envi
142. EDDED WORLD CHAPTER 2 mikroC for 8051 Environment The mikroC for 8051 is an user friendly and intuitive environment CHAPTER 2 Environment mikroC for 8051 IDE OVERVIEW mikrot for 8051 C Program FilesWikroelektranikaWmikroC 8051 Examples Led Blinking LedBlinking mc proj roe g Du ro BH zaa 2 fal IRR EET M gi LedBlinking mepro 25 Globals TypeDef Tags Includes Woid Code Assistant buit in Function Delay us const unsigned long Time In us Ubrary Manager p But inj function Delay const unsigned long Time In res E 12 19 moo Project Ledbbriking completed 312 Finished suceesshuli 19 mar 2008 13 09 32 The Code Editor features adjustable Syntax Highlighting Code Folding Code Assistant Parameters Assistant 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 be made 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 12 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment The source level So
143. ENDS O SLAVE SENDS bit6 1 ADDRESS WAS XORed with 1 IT WAS EQUAL STOP BYTE 0 ADDRESS UNCHANGED bit5 0 FIXED bit4 1 DATA3 if exists WAS XORed with 1 IT START BYTE or STOP BYTE 0 DATA3 if exists UNCHANGED bit3 1 DATA2 if exists WAS XORed with 1 IT START BYTE or STOP BYTE 0 DATA2 if exists UNCHANGED bit2 1 1 if exists WAS XORed with 1 IT START BYTE or STOP BYTE 0 1 if exists UNCHANGED bitlbitO 0 to 3 NUMBER OF DATA BYTES SEND CRC generation coro send datalen address crc send datal 01 y if exists crc send 11 ff if exists crc send datal 2 Jf If exists Cro Bend Cro pend IL send START BITE cre send cro Sendiri NOTE STOP BYTE 4 0 values DATALEN 4 0 can not take the START BYTE 4 mikroC for 8051 TO START BYTE or WAS EQUAL TO WAS EQUAL TO WAS EQUAL TO STOP BYTE 310 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries SOFTWARE LIBRARY The mikroC for 8051 provides routines for implementing Software communica tion These routines are hardware independent and can be used with any MCU The Software library enables you to use MCU as Master in communication Multi master mode is not supported Note This library implements time based activities so interrupts need to be dis abled when using Software
144. Enumerations for details about enum declarations POINTER CONSTANTS A pointer or pointed at object can be declared with the const modifier Anything declared as const cannot change its value It is also illegal to create a pointer that might violate a non assignability of the constant object Consider the following examples int 1 ff i is int int pi 77 mpl pointer to int uninitialized int const cp 61 is a constant pointer to inc const int ci 7 61 constant int const int pci pci is a pointer to constant int const int const cpc amp ci jf constant pointer LO a d d constant int The following assignments are legal 1 c 47 Assign constent to int top cis r Assign coDSt int to fe object pointed at by a const pointer Increment pointer to const pci cpc 44 Assign a const pointer to a const L0 d FE pointer to const MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 133 CHAPTER 5 Language Reference mikroC for 8051 The following assignments are illegal ci 0 f NO cannot assign to const int Cis NO cannot change const int 2 NO cannot assign to an object i pointed at by pointer to const 6 NO cannot assign to const pointer even if value would be unchanged Sorts NO cannot change const pointer pi pci NO if this assignment were allowed you would be a
145. Ethernet 337 opi Ethernet Disable 339 opi Ethernet doPacket 340 opi Ethernet putByte 341 opi Ethernet putBytes 341 opi Ethernet putConstBytes 342 opi Ethernet putString 342 opi _Ethernet_putConstString 343 opi Ethernet getByte 343 opi Ethernet getBytes 344 Spi_Ethernet_UserTCP 345 opi Ethernet 346 Library Example uu daas dod de oed erid dod e e 346 AW CONNECCION oul 354 SPI Graphic sac pao he fre 300 External dependencies of SPI Graphic LCD Library 355 EIDESEV ROUUNCS a c 290 _ 356 Spi Set Side sadn ese ooh ob fod OR GS Jof opi Set Page 397 Spi Sel X ig used sek om douce bk ERR redo tpa 358 opi Read Datla 358 opi Gled Write Data
146. Exit so we do not loop forever break do temp Man Receive amp error Attempt byte receive if error hed Chr EYrorlount tT If error occured Write question mark on LCD Update error counter Lit i iErrorcounk gt 20 f In case of multiple errors temp Man Synchro Try to synchronize again Man Receive Initt Alternativo try to Initialize Receiver again ErrorCount 0 else if temp OxOE If End byte was received see Transmitter example Loa Chr CP temp MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 281 7 No error occured CHAPTER 6 Libraries mikroC for 8051 Delay Malsa while temp OxOE Tf End byte was received exit do loop The following code is code for the Manchester transmitter it shows how to use the Manchester Library for transmitting data Manchester module connections sbit MANRXPIN at PO BO sbit MANTXPIN at P1 B1 End Manchester module connections char index character char sl mikroElektronika void main Man Send 1nit Initialize transmitter while 1 Endless loop Man Send 0x0B 77 Send start byte Delay ms 100 Wait for a while character 51 01 Take first char from string index 0 Initialize index variable while character f String ends with zero Man Send character Send character Delay ms 90 Wait for a while
147. ID Oxl0 f Het invalid else cleared 234 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries CANSPI RX XTD FRAME Set if XTD message else CANSPI RX FRAME 0x40 Set if RTR message else cleared CANSPI RX DBL BUFFERED 0x80 Set if this message was hardware double buffered You may use bitwise AND to adjust the appropriate flags For example Af iMsgElag amp CANSPI RX OVERFLOW 0 Receiver overflow has occurred We have lost our previous message CANSPI MASK The CANSPI MASK constants define mask codes Function CANSPISetMask expects one of these as it s argument const char CANSPI MASK B1 0 CANSPI MASK B2 1 CANSPI_FILTER The CANSPI FILTER constants define filter codes Functions CANSPISetFilter expects one of these as it s argument constr char CANSPI FILTER Bl Fl CANSPI FILTER Bl F2 CANSPI FILTER B2 Fl CANSPI FILTER B2 F2 CANSPI FILTER B2 F3 CANSPI FILTER B2 F4 CH 4 oq DX e Library Example This 1s 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SO
148. Jump Statements Compound Statements Blocks MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 201 CHAPTER 5 Language Reference mikroC for 8051 LABELED STATEMENTS Each statement in a program can be labeled A label is an identifier added before the statement like this label SLatenenr There is no special declaration of a label it just tags the statement Label identifier has a function scope and the same label cannot be redefined within the same function Labels have their own namespace label identifier can match any other identifier in the program A statement can be labeled for two reasons 1 The label identifier serves as a target for the unconditional goto statement 2 The label identifier serves as a target for the switch statement For this pu rpose only case and default labeled statements are used case constant expression statement default statement EXPRESSION STATEMENTS Any expression followed by a semicolon forms an expression statement expression The mikroC for 8051 executes an expression statement by evaluating the expres sion All side effects from this evaluation are completed before the next statement starts executing Most of expression statements are assignment statements or func tion calls A null statement 15 a special case consisting of a single semicolon The null statement does nothing and therefore is useful in situ
149. LD HAVE LIKED mC GLCD LIBRARY DEMO WELCOME r panel i f f Current panel General purpose register visibility Cursor position r Curs j Cposx i Clear 6963 ports init display for 240 pixel width and 128 pixel height 8 bits character width on PO control bus on Pi WR IRD UID RST TO OYGC 148 8 Enable both graphics text display at the same time ot MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 427 CHAPTER 6 Libraries mikroC for 8051 graphics 1 j panel 0 i 0 curs 0 cposy 0 Text messages LeXt LxL Uy 9 159630 MODE XOR 4 T6963C write Cext txtl 0 15 765963 ROM MODE Cursor T6963C cursor height 8 8 pixel height ser U i Move cursor to top left TRODIC GuFSOFID 3 Cursor off Draw rectangles T6262 rectangle rectangle T623620 rectangle rectangle Draw Crosse oF I6952C lane U Up 22 157 TOSOSC WHITE T69630 line D 127 239 0 T69530 WHITE Uy 29 141 WHITE j 2 20 7 413 107 T5353U WRITE 2 40 40 199 87 To96SC WHITE oU 179 57 WHITE 2 eee Draw solid boxes
150. LUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Expander_Set_PullUpsPortB Prototype void es set PullUpsPortB char ModuleAddress char Data Returns Nothing Description The function sets Port Expander s PortB pull up down resistors Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data for choosing pull up down resistors configuration Each bit corresponds to the appropriate pin of the PortB register Set bit enables pull up for corresponding pin Port Expander must be initialized See Expander Init Example Set Port Expander s PORTB pull up resistors Expander PullUpsPortB5B D 7 Expander Set PullUpsPortAB Prototype void Expander Set D END UNUS ModuleAddress unsigned int PullUps Returns Nothing Description The function sets Port Expander s PortA and PortB pull up down resistors Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page PullUps data for choosing pull up down resistors configurati on PortA pull up down resistors configuration is passed in PullUps s higher byte PortB pull up down resistors configura tion is passed in PullUps s lower byte Each bit corresponds to the appropriate pin of the PortA PortB register Set bit enables pull up for corresponding pin Port Expander must be initialized See Expander Init Example Set Port Expa
151. LUTIONS FOR EMBEDDED WORLD 235 CHAPTER 6 Libraries mikroC for 8051 Code for the first CANSPI node unsigned char Can Init Flags Can Send Flags Can Rev Flags CAN flags unsigned char Rx Data Len Received data length in bytes char RxTx Datal 8 y CAN rx tx data buffer char Msg Reception flag long Tx ID Bx ID CAN rx and tx ID CANSPI module connections LCangpi Pl BO Ret at End CANSPI module connections void main Can Init Flags 0 Send Flags 0 Clear flags Bov Flags 0 send Flags CAN TX PRIORITY D amp Form value to used CAN TX XTD FRAME amp gy with CANSPIWrite CAN TX NO RTR FRAME Can Init Flags CAN CONFIG SAMPLE THRICE amp oe Form value to be used CAN CONFIG PHSEG2 PRG ON amp with CANSPIInit CAN CONFIG XTD MSG amp CAN CONFIG DBL BUFFER 6 CAN CONFIG VALID XTD MSG ep Init Initialize SPI module LABSPIIBITIalISO l 2 9 1 C0aM Init Flags Initialize external CANSPI module CANSPISetOperationMode CAN MODE CONFIG OxFF 44 Set CONFIGURATION mode 236 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries CANSPISetMask CAN MASK 1 1 CONFIG XTD MSG 774 Set all maski bits to ones CANSPISetMask CAN MASK B2 1 CAN CONFIG XTD MSG 77 Set all mask bite to ones CANSPISetFIITCer C
152. Language Reference mikroC for 8051 for example T eguals 1 S 4 ds equals 5 ee buti ey Te Se 2 4 4 equals 5 25 because we are working with floats Remainder operand works only with integers the sign of result 1s equal to the sign of the first operand for example 9 2 equals 0 7 2 equals 1 X 2s eGuaie 1 Arithmetic operators can be used for manipulating characters amp 22 equals ASCII only TA de Tata eguals both ASCII and EBCDIC Unary Arithmetic Operators Unary operators and are the only operators in C which can be either prefix e g k k or postfix e g k k When used as prefix operators and preincrement and predecrement add or subtract one from the value of the operand before the evaluation When used as suf fix operators and postincrement and postdecrement add or subtract one from the value of the operand after the evaluation For example int j 5 k 1 1 which gives us 7 6 6 Dur int j 5 j k j 1 which gives us j 5 6 a 190 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference RELATIONAL OPERATORS Use relational operators to test equality or inequality of expressions If an expres sion evaluates to be true it re
153. Led Init routine Example Write text Here at current cursor position LEd Our Coi iere Lcd Chr Prototype void Lcd Chr char row char column char out char Description Prints character on LCD at specified position Both variables and literals can be passed as a character Parameters row Writing position row number column Writing position column number out char character to be written The LCD module needs to be initialized See Lcd Init routine Example character at row 2 Column 31 chri 2 71 266 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Lcd Chr Description Prints character on LCD at current cursor position Both variables and literals can be passed as a character Parameters out char character to be written Requires The LCD module needs to be initialized See Led Init routine Example Write B Current Cursor position Log Cnr Cpe Lcd Cmd Description Sends command to LCD Parameters out char command to be sent Note Predefined constants can be passed to the function see Available LCD Commands The LCD module needs to be initialized See Lcd Init routine Example Clear LCD display Lcd Cmd LCD CLEAR MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 267 CHAPTER 6 Libraries mikroC for 8051 Available LCD Commands R
154. MBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries T6963C PanelFill Prototype void 6963 PanelFill unsigned char v Description Fill current panel in full graphic text with appropriate value 0 to clear Parameters v value to fill panel with Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Example cieer Current panel Telos Panelrill 0 T6963C GrFill Prototype void T6963C GrFill unsigned char v Description Fill current graphic panel with appropriate value 0 to clear Parameters v value to fill graphic panel with Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Example clear current graphic panel T6963C GrFill 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 423 CHAPTER 6 Libraries mikroC for 8051 T6963C TxtFill Prototype void 6963 TxtFill unsigned char v Description Fill current text panel with appropriate value 0 to clear Parameters this value increased by 32 will be used to fill text panel Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Example clear current text panel IO T6963C Cursor Height Prototype void T6963C Cursor Height unsigned char n Description Set cursor size Parameters n cursor height Valid values 0 7 Requires Toshiba GLCD module needs to be initial
155. ND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 Directives elif Zelse and endif Directives Zifdef and Zifndef mikroC for 8051 Libraries Hardware 8051 specific Libraries Standard ANSI C Libraries Miscellaneous Libraries Library Dependencies CANSPI Library External dependecies of CANSPI Library Library Routines CANSPISetOperationMode CANSPIGetOperationMode CANSPIInitialiaze CANSPISetBaudRate CANSPISetMask CANSPISetFilter CANSPIRead CANSPI Constants CANSPI OP MODE CANSPI CONFIG FLAGS CANSPI TX MSG FLAGS CANSPI RX MSG FLAGS CANSPI MASK 5 _ Library HW Connection EEPROM Library Library Routines Eeprom Read Eeprom Write Eeprom Write Block Library Example Table of Contents MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XV Table of Contents mikroC for 8051 Graphic LCD Library
156. NS FOR EMBEDDED WORLD Table of Contents mikroC for 8051 Read 433 WING er 434 eer Ro ed 434 This example demonstrates s 434 AVY COMMECUON Pm 435 ANSI C Ctype Library scura m aye eee ad ERG casica des hae inbiria 436 Library FUNCUONS ofa dr hh et dic EROR drap e od 436 M de oe ora tyne ae ee oc ee a ae ee gah ws ere ee ead Segue a 436 Il oo Bae eee ee ae oe oes ged 436 ISCO bees dee ede ee 437 rol aee 437 ISOM 5 5 2 62 owt oe ee A eh 437 ob cr moe ee eee es eee E Feed ee mand 437 mue fee oes baer he 437 eca cece pease 437 je ose 438 aes es TRES 438 438 he tee he ae a ee ee 438 ANSI C Math Library 439 Library FUNCUONS anh ete ra doner 439 co
157. OFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries KEYPAD LIBRARY The mikroC for 8051 provides a library for working with 4x4 keypad The library routines can also be used with 4x1 4x2 or 4x3 keypad For connections explana tion see schematic at the bottom of this page Note Since sampling lines for 8051 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 External dependencies of Keypad Library Library Routines The following variable must be defined in all projects using Keypad Description Example Library sfr Keypad Port sfr char de eypadPort at P0 Keypad Init Keypad Key Press Keypad Key Click Keypad Init Initializes port for working with keypad keypadPort variable must be defined before using this function Example Initialize for communication with keypad sfr char keypadPort at Keypad Init MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 259 CHAPTER 6 Libraries mikroC for 8051 Keypad Key Press Returns The code of a pressed key 1 16 If no key is pressed returns 0 Reads the key from keypad when key gets pressed Requires Port needs to be initialized for working with the Keypad library see Keypad Init Example char kp e
158. OFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 Lcd Init Initializes LCD module Requires Global variables LCD D7 data bit 7 LCD D6 data bit 6 LCD D5 data bit 5 LCD D4 data bit 4 RS register select data instruction signal pin EN enable signal pin must be defined before using this function Example icd pinout settings sbit Bis sbit 512 sbit SEO sbit 4 sbit 4022 sbit Big lo Inici Lcd Out LCD RS LCD EN Lo p LCD D6 LCD D5 LCD D4 at at at at at at Pa P2 PZ P2 Ps CHAPTER 6 Libraries BO B4 B3 Prototype void Lcd Out char row char column char text Nothing Description Prints text on LCD starting from specified position Both string variables and literals can be passed as a text Parameters row Starting position row number column starting position column number text text to be written The LCD module needs to be initialized See Lcd Init routine Example Write text Hello on LCD starting from row 1 colum 33 Led Oucily 3 Hello MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 265 CHAPTER 6 Libraries mikroC for 8051 Lcd Out Description Prints text on LCD at current cursor position Both string vari ables and literals can be passed as a text Parameters text text to be written Requires The LCD module needs to be initialized See
159. ONS FOR EMBEDDED WORLD 195 CHAPTER 5 Language Reference mikroC for 8051 Logical vs Bitwise Be aware of the principle difference between how bitwise and logical operators work For example 0222222 amp 903525929 equals 000000 0422522 09239223 equals 1 se Ou A434 equals OxEDCB 0x1234 equals 0 CONDITIONAL OPERATOR The conditional operator is the only ternary operator in C Syntax of the condi tional operator is expressionl expression2 expression3 The expressioni is evaluated first If its value is true then expression2 evaluates and expression3 15 ignored If expression1 evaluates to false then expression3 evaluates and expression is ignored The result will be a value of either expres sion2 Of expression3 depending upon which of them evaluates Note The fact that only one of these two expressions evaluates is very important if they are expected to produce side effects Conditional operator associates from right to left Here are a couple of practical examples y Find max a b max a gt b a b Convert small letter to capital no parentheses are actually necessary qoe 0 Tat 26 G lt gt 38 t o0 Conditional Operator Rules expression1 must be a scalar expression expression2 and expression3 must obey one of the following rules 196 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CH
160. OR EMBEDDED WORLD 351 CHAPTER 6 Libraries mikroC for 8051 len putConstString indexPage HTML page first part len putConstString indexPage2 HTML page second part return len return to the library with the number of bytes to transmit pe HIS funotion called by the Library the user accesses to the UDP request by successive calls to Ethernet getBvteij the user puts data in the transmit buffer by successive calls CG Spi the function must return the length in bytes of the UDP reply or 0 if not ing to transmit if you don t need to reply to UDP requests just define this function with a return 0 as single statement unsigned int Spi Ethernet UserUDP unsigned char remoteHost unsigned int remotePort unsigned int destPort unsigned int reqLength idata unsigned int len my reply length idata unsigned char ptr pointer to the dynamic buffer 44 reply is made of the remote host IP address in human readable format ByteToStr remoteHost 0 dyna first IP address byte 3 j ByteToStr remoteHost 1 dyna 4 Ky second 7 ByteToStr remoteHost 2 dyna 8 third 11 ByteToStri remoteHost 3 dyna 4 12 fourth ovis 15 227 3 add separator then remote host port number WordToStr remotePort dyna 16 dyna 21 WordToSLtr iOestPort
161. ORLD CHAPTER 6 mikroC for 8051 Libraries SPRINT LIBRARY The mikroC for 8051 provides the standard ANSI C Sprintf function for easy data formatting Note In addition to ANSI C standard the Sprint Library also includes two limited versions of the sprintf function sprinti and sprintl These functions take less ROM and RAM and may be more convenient for use in some cases Functions sprintf sprintl sprinti sprintf Prototype Sprintf char wh const char f Returns function returns the number of characters actually written to destination string Description sprintf is used to format data and print them into destination string Parameters wh destination string f format string The f argument is a format string and may be composed of char acters escape sequences and format specifications Ordinary characters and escape sequences are copied to the destination string in the order in which they are interpreted Format specifica tions always begin with a percent sign gt and require additional arguments to be included the function em The format string is read from left to right The first format speci fication encountered refers to the first argument after f and then converts and outputs it using the format specification The second format specification accesses the second argument after f and so on If there are more arguments than format specifications then these extra arguments are ig
162. ORLD mikroC for 8051 Table of Contents Library Routines 311 SOM IZ6 MW oat peeks Go oes eree 312 SOIL 1207 ario ond hee eee Coe ee 312 REAU 644 ic shade dic on nee be 312 MU Om AMET 319 SIOD 343 5 cohen E REG ERG eee bee E Ed 219 Library 314 Software SPI Library 317 External dependencies of Software SPI Library 317 Library ROUUNCS scsi ces 4x2 dg oho deeds Depew deed 317 dos mui 317 Soft Spi Read 317 SOR OPI YVE 317 SON OPI NM srera eo ae ka ee Ree Pee ee TET 318 SOR 200 ISO dL seeds sene eee ee eae 318 Soft Spi 319 Libian Example v 320 Software UART Library 322 External dependencies of Software UART Library 322 Library Routines 322 SOIL Vat e end 323 Solt 323 Soft Uart 324 baton cena ee 324
163. PTER 6 mikroC for 8051 Libraries Library Routines Spi T6963C Config Spi T6963C WiriteData Spi T6963C WriteCommand Spi T6963C SetPtr Spi T6963C WaitReady Spi T6963C Fill Spi T6963C Dot Spi T6963C Write Char Spi T6963C Wirite Text Spi T6963C Line Spi T6963C Rectangle Spi T6963C Box Spi T6963C Circle Spi T6963C Image Spi T6963C Sprite Spi T6963C Set Cursor Note The following low level library routines are implemented as macros These macros can be found in the spi 76963c n header file which is located in the SPI T6963C example projects folders 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 385 CHAPTER 6 Libraries mikroC for 8051 Spi_T6963C_Config Prototype void Spi T6963C Config unsigned int width unsigned char height unsigned char fntW char DeviceAddress unsigned char wr unsigned char rd unsigned char cd unsigned char rst Description 386 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Initalizes the Graphic Lcd controller Parameters width Width
164. PortB and Expander Set DirectionPortAB routines Example Read byte from Port Expander s PORTA and PORTB unsigned int read data Bxpatder Set DirsectionPoOrPtaBiD UEXPEPFP set expander s porta and portb to be input read data Expander Bead POrLAB O 288 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Expander_Write_PortA Prototype void Expander Write PortA char ModuleAddress char Data 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 Expander Set DirectionPortAB routines Example Write a byte to Port Expander s PORTA Expander Ser 0 08007 set expander s porta to be output Expander Write PortA 0 Expander_Write_PortB Prototype void Expander Write PortB char ModuleAddress char Data Description function writes byte to Port Expander s PortB Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written Requires Port Expander must be initialized See Expander Init Port Expander s PortA should be configured as output See Expander Set DirectionPortA and Requires Port Expander must be initialized See Expander Init Port Expander s PortB should be configured as output See
165. Project Linked Successfully All files Preprocessed in 551 ms All files Compiled in gt s ms Linked in gt s ms Project s completed 5 ms COMPILER WARNING MESSAGES Illegal file type 551 Bad or missing fosc parameter Default value 8MHz used Specified search path do not exisit 551 Specified include path do not exisit 251 Result is not defined in function sj Initialization of extern object 551 Suspicious pointer conversion Implicit conversion of pointer to int Unknown pragma line ignored 251 Implicit conversion of int to Generated baud rate 151 s bps error 5 percent Unknown memory model gt s small memory model used instead MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 89 CHAPTER 2 Environment mikroC for 8051 SOFTWARE SIMULATOR OVERVIEW The Source level Software Simulator is an integral component of the mikroC for 8051 environment It is designed to simulate operations of the 8051 MCUs and assist the users in debugging C code written for these devices After you have successfully compiled your project you can run the Software Simulator by selecting Run Start Debugger from the drop down menu or clicking the Start Debugger Icon from the Debugger Toolbar Starting the Software Simulator makes more options available Step Into Step Over Step Out Run to Cursor etc Line that is
166. R EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference Scope and visibility usually coincide though there are circumstances under which an object becomes temporarily hidden by the appearance of a duplicate identifier the object still exists but the original identifier cannot be used to access it until the scope of the duplicate identifier ends Technically visibility cannot exceed a scope but a scope can exceed visibility See the following example void f int i int Ji auto by default j 3 int i and j are in scope and visible nested block double j j is local name in the nested block 7 0 1 i and double j are visible int 7 3 in scope but hidden double 1 out of scope j 1 int j visible and 4 4 4 i and j are both out of scope NAME SPACES Name space is a scope within which an identifier must be unique The mikroC for 8051 uses four distinct categories of identifiers 1 goto label names must be unique within the function in which they are declared 2 Structure union and enumeration tags must be unique within the block in which they are defined Tags declared outside of any function must be unique 3 Structure and union member names must be unique within the structure or union in which they are defined There is no restriction on the type or offset of members with the same member name in different structures 4 Variables typedefs functions and enumeration member
167. RE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 include TOSDOL AI fe bitmap pictures stored in ROM extern const code char mc extern const code char einstein Port Expander module connections sbit SPExpanderRST at P1 B0 sbit SPExpanderCS at 1 1 End Port Expander module connections void main char idata txtl EINSTEIN WOULD HAVE LIKED mC char idata txt GLCD LIBRARY DEMO WELCOME unsigned char panel current panel unsigned int 3 2 general purpose register unsigned char CUTS 3 jf Cursor visibility unsigned int cposy cursor x y position PO 255 Configure PORTO as input init display for 240 pixel width and 128 pixel height 8 bits character width Dus on MGCPSOSIZ ports control bus on 2 517 porta bir 2 INR I IFD DILD D LS ICD hit 2 RST Initialize SPI module Spi Init Advanced MASTER OSC DIV4 CLK IDLE LOW DATA ORDER MSB Initialize SPI Toshiba 240x128 opi TOSSSC Conriqgi240 128 8 0 2 Delay ms 1000 Enable both graphics and text display at the same time TesosC graphices l Textil 4 CHAPTER 6 Libraries chip enable reverse on 8x8 font internaly set in library IDLE 2 ACTIVE MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 403 CHAPTER 6 Libraries mikroC for 8051 panel 0
168. RLD 295 CHAPTER 6 Libraries mikroC for 8051 PS 2 LIBRARY The mikroC for 8051 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 6MHz 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 proj Description Example ects using PS 2 Library extern sbit PS2 DATA PS 2Dataline spit PS2 DATA at extern sbit PS2 CLOCK PS 2 Clock line sb t PS2 CLOCK at PO B1 Library Routines Ps2 Config Ps2 Key Read Ps2 Config Prototype void Ps2 Config Returns Nothing Description Initializes the MCU for work with the PS 2 keyboard Requires Global variables PS2 DATA Data signal pin PS2_CLOCK Clock signal pin must be defined before using this function Example PS2 pinout definition sbit PS2 DATA at sbit 52 CLOCK at 1 Pas Contig Init PS 2 Keyboard 296 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Ps2 Key Read Prototype unsigned short
169. RLD 381 CHAPTER 6 Libraries mikroC for 8051 Library Example This example demonstrates how to communicate LCD in 8 bit mode via the SPI module using serial to parallel convertor MCP23S17 char text mikrok Port Expander module connections sbit SPExpanderRST at P1 B0 sbit SPExpanderCS at 1 1 End Port Expander module connections void main 44 Initialize SPI interface Spi Leds Contig 44 Intialize LCD in 8bit mode via SPI Spi Cmd LCD CLEAR Clear display Spi Lod8 Cmd LCD CURSOR OFF fr Turm GUPrBOF Off opi Lede Text if Print text to DCO Pow Dt Colm 5 beds Che CB IT 3 Append opi Ledo Qurisz l mikroslekrtronilka Print text to BCD 2nd row colums Sol LOCO 00202 1 Denes For LCD modules with more than two rows 10209 Vutia 13 For LCD modules with more than two rows 382 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries HW Connection 23517 wu o VCC GC8S68 1V OSCILLATOR VC Contrast Adjustment 6 15 SPI LCD8 HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 383 CHAPTER 6 Libraries mikroC for 8051 SPI T6963C GRAPHIC LCD LIBRARY The mikroC for 8051 provides a library for working with GLCDs based o
170. RONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi_Glcd_Write_Data Prototype void Spi Glcd Write Data char Ddata Description Writes one byte to the current location in GLCD memory and moves to the next location Parameters pdata data to be written Requires GLCD needs to be initialized for SPI communication see Spi Init routines GLCD side x axis position and page should be set first See the functions Spi Gled Set Side Spi Gled Set X and Spi Set Page Example char data Spi Glcd Write Data data Spi Glcd Fill Prototype void Spi Glcd Fill char pattern Description Fills GLCD memory with byte pattern Parameters pattern byte to fill GLCD memory with To clear GLCD screen use spi G1cd Fill 0 To fill the screen completely use Spi Gicd Fill OxFF Requires GLCD needs to be initialized for SPI communication see Spi Gled Init routines Example Clear screen CPL 131008 PLLLQO MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 359 CHAPTER 6 Libraries mikroC for 8051 Spi Glcd Dot Prototype void Spi Glcd Dot char x pos char y pos char color Description Draws a dot on GLCD at coordinates x pos y pos Parameters x pos X position Valid values 0 127 y pos y position Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the dot state 0
171. Replace Text 17 PIG TOM acta bees 17 LING MC 18 WG FOS is oy od eS wae ee Ee 18 Regular expressions 19 View Men OpHONS 4 599292 20 Edit Toolbar 21 TOOD cq m aee aa e 21 File Toolbar 21 Advanced Edit 22 Project 23 Find Replace 23 Brlv PPM 24 TOODA MTM 24 won is es meanma wea mae eG eee 25 EM 26 iv MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 Table of Contents Project Menu Options 27 R n Men ORUONS CR e 29 Tools Menu 5 30 Help Menu OptionS 31 Keyboard ShOr CU S e 22 3x29 accedo edad e Elser RC aee dd ea 92 IDE 555550525 54 ru S ees 36 Customizing IDE Layout
172. SFR GPR ROM S ROM Allocation 3 Procedures See Locations 0204 0 020000 00 0 020000 OxO00 0 020000 00 00 0 020000 x 0 00 Procedures Windows Provides overview procedures locations and sizes Procedures Size Window Displays size of each procedure Statistics Memon Usage jac ROM usage by procedure ROM locations a M data iD ata ata ROM Allocation Procedures Locations i i i 4 4 1 E 1 1 1 m am 200 300 locations MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 57 CHAPTER 2 Environment mikroC for 8051 Procedures Locations Window Displays how functions are distributed in microcontroller s memory Statistics Memor Usage Data data iD ata bD ata Pdata SFH GPR ROM Allocation Procedures Procedures by ROM location Macro Editor A macro 15 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 Macro Editor 58 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environme
173. SOH STX ETX EOT ENQ ACK BEL BS HT LF 0 1 2 3 4 5 6 7 o 9 10 1 12 DLE DC1 DC2 DC3 DC4 SYN ETB CAN EM SUB ESC FS 18 2u 2 22 4 26 11 34 2 50 5 2 a 5 re BF Pp 1 E 4 4 i B 1 eT i a F e 9 2 E mm em PEN 224 FE 2 2 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 61 CHAPTER 2 Environment mikroC for 8051 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 EEP ROM 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 mikroC for 8051 IDE project name hex file will be loaded automatically while ihex file must be loaded manually EEPROM Editor Address Bx FF Load Data Memory Size 2045 Bytes value Save 4 Use this EEPROM definition 1 T 1 Ul 7 m 1 m 1 m n mim 1mm 62 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 3 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 6 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 7
174. SPI module into configuration mode wait inside CANSPISetOperationMode until this mode is set CANSPISetOperationMode CANSPI MODE CONFIG OxFF 224 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries CANSPIGetOperationMode Prototype char CANSPIGetOperationMode void Returns Current operation mode Description The function returns current operation mode of the CANSPI mod ule Check cANSPI MODE constants see CANSPI constants or device datasheet for operation mode codes Requires The CANSPI routines are supported only by MCUS with the SPI module MCU has to be properly connected to mikroElektronika s CAN SPI Extra Board or similar hardware See connection example at the bottom of this page Example check whether the CANSPI module is in Normal mode and if it is do something if CANSPIGetOperationMode CANSPI MODE NORMAL MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 220 CHAPTER 6 Libraries mikroC for 8051 CANSPIInitialize Prototype void CANSPIInitialize char SJW char BRP char 5 char PHSEG2 char PROPSEG char CAN CONFIG FLAGS Description Initializes the CANSPI module Stand Alone CAN controller in the CANSPI module 15 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 par
175. Sound Init 77 Initialize sound pin MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 327 CHAPTER 6 Libraries mikroC for 8051 Sound Play 2000 1000 Play starting sound 2kHz 1 second while 1 endless loop if 7 If 1 7 is pressed play Tonel 1 oF while j Wait for button to be released i IIPL 61 If P1 6 is pressed play Tone2 Tone2 while P1 6 f Wait for button to be released ae LIB SJ If P1 5 is pressed play Tone3 Tone3 oF while P1 5 Wait for button to be released if 1 4 If 1 4 is pressed play Melody2 Melody2 while 4 r Wait for button to be released af If 1 3 is pressed play Melody Melody 77 while 1 3 Wait for Button to be released HW Connection el PIEZO a SPEAKER vcc Ho VCC 1 3 L P1 B4 6 10 Example of 5 Sound Library con 1 6 nection h 2 P1 B7 54 085681 OSCILLATOR VCC XTAL1 GND 328 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries SPI LIBRARY mikroC for 8051 provides a library for comfortable with SPI work in Master mode The 8051 MCU can easily communicate with other devices via SPI A D convert ers D A converters MAX7219 LTC1290 etc Library Routines Sp
176. TO PC data Rx 1 1 uM e CABLE 4 End PC TO MCU Data Tx SUB D 9p 54 085681 6 18 UART HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 435 CHAPTER 6 Libraries mikroC for 8051 ANSI C CTYPE LIBRARY The mikroC for 8051 provides a set of standard ANSI C library functions for test ing and mapping characters Note Not all of the standard functions have been included Note The functions have been mostly implemented according to the ANSI C stan dard but certain functions have been modified in order to facilitate 8051 program ming Be sure to skim through the description before using standard C functions Library Functions isalnum isalpha iscntrl isdigit isgraph islower ispunct isspace isupper isxdigit toupper tolower isalnum Prototype unsigned short isalnum char character Function returns 1 if the character 15 alphanumeric A Z a z 0 9 otherwise returns zero isalpha Prototype unsigned short isalpha char character erwise returns zero Function returns 1 if the character 15 alphabetic A Z a z oth 436 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries iscntrl Prototype unsigned short iscntrl char character Description Function returns if the character is a control or dele
177. This is also true for signed operands if all discarded bits are equal to a sign bit MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 193 CHAPTER 5 Language Reference mikroC for 8051 000001 lt lt 3 equals 000040 DESSBOL lt 4 equals 0x8010 overflow With shift right gt gt far right bits are discarded and the freed bits on the left are assigned zeroes in case of unsigned operand or the value of a sign bit in case of signed operand Shifting operand to the right by positions is equivalent to divid ing it by 24 xFF5O gt gt 4 equals OxFFF5 OxFF56u gt gt 4 equals OxOFF5 Bitwise vs Logical Do not forget of the principle difference between how bitwise and logical operators work For example amp Do90523 equals 000000 092233293 equals 1 Dx1234 equals OxEDCB 04127345 equals 0 LOGICAL OPERATORS Operands of logical operations are considered true or false that 1s non zero or zero Logical operators always return 1 or 0 Operands in a logical expression must be of scalar type Logical operators and associate from left to right Logical negation operator associates from right to left Logical Operators Overview 194 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference Logical Operations Precedence of logical r
178. UND STATEMENTS BLOCKS The compound statement or block is a list possibly empty of statements enclosed in matching braces Syntactically the block can be considered to be a single statement but it also plays a role in the scoping of identifiers An identifier declared within the block has a scope starting at the point of declaration and ending at the closing brace Blocks can be nested to any depth up to the limits of memory MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 209 CHAPTER 5 Language Reference mikroC for 8051 For example the for loop expects one statement in its body so we can pass it a com pound statement for i 0 1 lt n i 4 int temp aa als 1 temp Note that unlike other statements compound statements do not end with semicolon ke there is never a semicolon following the closing brace PREPROCESSOR Preprocessor is an integrated text processor which prepares the source code for com piling Preprocessor allows inserting text from a specifed file to a certain point in the code see File Inclusion replacing specific lexical symbols with other symbols see Macros conditional compiling which conditionally includes or omits parts of the code see Conditional Compilation Note that preprocessor analyzes text at token level not at individual character level Preprocessor is controled by means of preprocessor directives and preprocessor
179. UT Performs project wide init initialize Sort IZC communication 77 Initialisze LCD Clear LCD display Tarn curser OIX Prepare and output static text on LCD 219 CHAPTER 6 Libraries mikroC for 8051 Main procedure void main Init Main Perform initialization while 1 Endless loop Bead Times Read time from RTC PCF8583 Transform Time Format date and time Display Time Prepare and display on LCD Delay ms 1000 Wait 1 second 316 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries SOFTWARE SPI LIBRARY The mikroC for 8051 provides routines for implementing Software SPI communi cation These routines are hardware independent and can be used with any MCU The Software SPI Library provides easy communication with other devices via SPI A D converters D A converters MAX7219 LTC1290 etc Library configuration SPI to Master mode Clock value 20 kHz Data sampled at the middle of interval Clock idle state low Data sampled at the middle of interval Data transmitted at low to high edge 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 vari ables must be defined T Description Example in all projects using Software SPI Library extern sbit Data In line
180. WORLD CHAPTER 6 mikroC for 8051 Libraries Spi T6963C sprite 76 4 einstein 88 119 Draw a sprite Spi T6963C setGrPanel 1 Select other graphic panel Spi T6963C image mc Fill the graphic screen with a picture for I Endless loop 5 U pressed toggle display Detween graphic panel 0 graphic 1 UJ 4 1 panel amp 1 T5953 displayerPrane panel Delay ms 300 fe IT PU I pressed display only graphic panel a else if PO 1 ToS63C 1 j opa TOC 4 Delay ms 300 oe If 2 28 pressed display only text panel else if PO 2 Tb59630 Delay msts0D jf If 2 pressed display text and graphio panels else if PO 3 1 TOSOSL 2 Delay ms 300 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 405 CHAPTER 6 Libraries mikroC for 8051 If pressed Change cursor else if PO 4 3 if curs 3 curs 0 switch curs case 0 r no cursor Spi T6963C cursor 0 break case 1 blinking cursor cursor l opi 702630 cursor Dlink l s break case 2 non blinking cursor opa 7096032 11 opa Teves GUPSOP Dlink U
181. Width width of the font characters in dots aFontHeight height of the font characters in dots aFontOffs number that represents difference between the mikroC for 8051 character set and regular ASCII set eg 1f A 1s 65 1n ASCII character and A 1s 45 in the mikroC for 8051 character set aFontOffs 15 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 c file located 1n the Uses folder or create his own fonts GLCD needs to be initialized see Gled Init routine Example Use the custom 5x7 font myfont which starts with space 32 Glod Set Font myiont 5 7 32 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 253 CHAPTER 6 Libraries mikroC for 8051 Glcd Write Char Prototype void Glcd Write Char unsigned short chr unsigned short x pos unsigned short page num unsigned short color Returns Nothing 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 botto
182. aa OK same type member by member assignment aa bb ILLEGAL different types but you can assign member by member 1 bb i bb j aa d bb d 166 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference UNIONS Union types are derived types sharing many of syntactic and functional features of structure types The key difference is that a union members share the same memory space Note The mikroC for 8051 does not support anonymous unions ANSI divergence Union Declaration Unions have the same declaration as structures with the keyword union used instead of struct union tag member declarator list Unlike structures members the value of only one of union s members can be stored at any time Here is a simple example union myunion union tag is myunion int i double d char ch t The identifier mu of the type myunion can be used to hold a 2 byte int 4 byte double or single byte char but only one of them at a certain moment The identifi er pm 15 a pointer to union myunion Size of Union The size of a union 1s the size of its largest member In our previous example both sizeof union myunion and sizeof mu return 4 but 2 bytes are unused padded when mu holds the int object and 3 bytes are unused when mu holds char Union Member Access Union members be accessed with the s
183. ace to store the result The function returns address of the object pointed to by to MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 449 CHAPTER 6 Libraries mikroC for 8051 strchr Prototype char strchr char ptr char chr Description Function locates the first occurrence of character chr in the string ptr The function returns a pointer to the first occurrence of char acter chr or a null pointer if chr does not occur in ptr The ter minating null character is considered to be a part of the string strcmp Prototype int strcmp char 51 char 52 Description Function compares strings si s2 and returns zero if strings are equal or returns a difference between the first differing characters in a left to right evaluation Accordingly the result is greater than zero if 51 is greater than s2 and vice versa strcpy Prototype char strcpy char to char from Description Function copies the string from into the string to If copying is successful the function returns to If copying takes place between objects that overlap the behavior is undefined strlen Prototype int strlen char 5 Description Function returns the length of the string s the terminating null character does not count against string s length strncat Prototype char strncat char to char from int size Description Function appends not more than size characters from the
184. ags need to be cleared by software Requires MCU must be initialized as a Master for RS 485 communication See Rod omaster_ Example char ms g RS485master Receive meq RS485master_Send void Rs485master Send char data buffer char pe slave address Nothing Description Sends message to Slave s Message format can be found at the bottom of this page Parameters data buffer data to be sent datalen number of bytes for transmition Valid values 0 3 slave address Slave s address Requires MCU must be initialized as a Master for RS 485 communication See RS485master Init It is the user s responsibility to ensure by protocol that only one device sends data via 485 bus at a time Example char msg 8 send 3 bytes of data to slave with address 0x12 RS4B5master Send msg 3 0 12 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 303 CHAPTER 6 Libraries mikroC for 8051 RS485slave Init Prototype void EHs485slave Init char slave address Description Initializes MCU as a Slave for RS 485 communication Parameters Slave address Slave address Requires rs485 transceive variable must be defined before using this function This pin is connected to RE DE input of RS 485 trans schematic at the bottom of this page RE DE signal controls RS 485 transceiver operation mode Valid values 1 for transmitting and 0 for receiv
185. alphabetical listing of keywords in asm break Conse continue default dO double else enum extern Float Tor JOCO 3T ant Long register Shere Signed sizeof Brac SLIUPL switch typedef union unsigned Void volatile while Also the mikroC for 8051 includes a number of predefined identifiers used in libraries You could replace them by your own definitions if you want to develop your own libraries For more information see mikroC for 8051 Libraries MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 135 CHAPTER 5 Language Reference mikroC for 8051 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 get confused with the meaning of object in object oriented programming 66 92 Identifiers can contain the letters a to z and A to Z underscore character digits 0 to 9 The only restriction is that the first character must be a letter or an underscore Case Sensitivity The mikroC for 8051 identifiers are not case sensitive by default so that sum sum and suM represent an equivalent identifier Case sensitivity can be activated or sus pended in Output Settings window Even
186. am in which the identifier can be used to access its object There are different categories of scope block or local func tion function prototype and file These categories depend on how and where iden tifiers are declared Block The scope of an identifier with block or local scope starts at the decl aration point and ends at the end of the block containing the declaration such block is known as the enclosing block Parameter declarations with a function definition also have block scope limited to the scope of the function body File File scope identifiers also known as globals are declared outside of all blocks their scope is from the point of declaration to the end of the source file Function The only identifiers having function scope are statement labels Label names can be used with goto statements anywhere in the function in which the label is declared Labels are declared implicitly by writing label name followed by a statement Label names must be unique within a function Function prototype Identifiers declared within the list of parameter declara tions in a function prototype not as a part of a function definition have a function prototype scope This scope ends at the end of the function prototype Visibility The visibility of an identifier 1s a region of the program source code from which an identifier s associated object can be legally accessed 142 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FO
187. ameters CAN mode Normal Filter and mask registers IDs are set to zero Filter and mask message frame type 15 set according to CONFIG FLAGS value SAM SEG2PHTS WAKFIL and DBEN bits are set according to CAN CONFIG FLAGS value Parameters sow as defined CAN controller s datasheet BRP as defined in CAN controller s datasheet 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 1s formed from predefined constants see CANSPI constants Requires CanSpi CS and CanSpi Rst variables 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 Spi Init and Spi Init Advanced routines MCU has to be properly connected to mikroElektronika s CAN SPI Extra Board or similar hardware See connection example at the bottom of this 1 226 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Example initialize the CANSPI module with the appropriate baud rate and message acceptance flags along with the sampling rules char Can Init Flags Can Init Flags CAN CONFIG SAMPLE THRICE amp 77 form value to be used CAN CONFIG PHSEG2 PRG ON amp if with CANSPIrIinitialize CAN CONFIG XTD MSG amp CAN CONFIG DBL BUFFER 6 CAN CONFIG VALID XTD MSG
188. ani a i EE E E 207 Break and Continue Statements 207 Break Statement 207 Continue Statement 208 Goto Statement 208 Return Statement 209 Compound Statements Blocks 209 PICDIOCESSO da adul 210 Preprocessor Directives 210 Line Continuation with Backslash 211 P m 211 Defining Macros and Macro Expansions 211 Macros with Parameters 213 Undefining 214 File P TT 214 aa cece be ad Lecce om ser shee gs geste he hcg 215 NOW 26665480 wee een hs HE eas 215 Preprocessor Operators 215 8er F ne 215 Ar 216 NODO 216 Conditional Compilation 217 xiv MIKROELEKTRONIKA SOFTWARE A
189. any number of expressions expression 1 SXpreseion 2 s eXDpression ni 200 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference which results the left to right evaluation of each expression with the value type of expression n giving the result of the whole expression Results of other expressions are discarded but their possible side effect do occur For example result 5 b 2 ct returns preincremented value of variable c but also intializes a divides b by 2 and increments c result x 10 y x 3 zZz x 3 y returns computed value of variable z and also computes x and y Note Do not confuse comma operator sequence operator with comma punctuator which separates elements in a function argument list and initializator lists To avoid ambi guity with commas in function argument and initializer lists use parentheses For example func i J 1 4 ki calls the function func with three arguments 1 5 k not four STATEMENTS Statements specify a flow of control as the program executes In the absence of spe cific jump and selection statements statements are executed sequentially in the order of appearance in the source code Statements can be roughly divided into Labeled Statements Expression Statements Selection Statements Iteration Statements Loops
190. aphic operations wi preformed at this graphic pane Description Requires Parameters graphic panel number Valid values 0 and 1 Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example set graphic panel 1 as current graphic panel 159832 SerGrPanel 1 Spi T6963C SetTxtPanel Prototype void Spi T6963C SetTxtPanel char n Description Compute start address for selected text panel and set appropriate internal pointers All subsequent text operations will be preformed at this text panel Parameters text panel number Valid values 0 and 1 Toshiba GLCD module needs to be initialized See Requires Tost T6963C_ Config routine Example set text panel 1 as poe text Panel TO7630 SOLTXELPSnel 398 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi T6963C PanelFill Prototype void Spi T6963C PanelFill unsigned char v Description Fill current panel in full graphic text with appropriate value 0 to clear Parameters v value to fill panel with Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example clear current panel epi I6963 Panel 11l10 j Spi T6963C GrFill Prototype void Spi T6963C GrFill unsigned char v Description Fill current graphic panel with appropriate value 0 to clear Parameters v value
191. apse complex variables struct type variables strings Values are updated as you go through the simulation Recently changed items are colored red Watch Values Hs TBSB3L crcle 4 e Mame Value Address T6863C cntlrsE 0 0094 T6863C grWidth 0020 Pi Cycle 560 00 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 91 CHAPTER 2 Environment mikroC for 8051 Double clicking a variable or clicking the Properties Button 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 typ ing the new value directly Edit Value 0100 0000 1000 0011 0001 001001101111 Representation oy eL oy Hex i Float 2 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 Software Simulator action Stopwatch measures the execution time number of cycles from the moment Software Simulat
192. ariable but with ahead of identifier A type at the beginning of declaration specifies the type of a pointed object A point er must be declared as pointing to some particular type even if that type 15 voia which really means a pointer to anything Pointers to void are often called generic pointers and are treated as pointers to char in the mikroC for 8051 154 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference If type 5 any predefined or user defined type including void the declaration type p Uninitialized pointer declares to be of type pointer to type All scoping duration and visibility rules are applied to the p object just declared You can view the declaration this way if Is an object of type then has to be a pointer to such object object of type Note You must initialize pointers before using them Our previously declared point er is not initialized 1 assigned a value so it cannot be used yet Note In case of multiple pointer declarations each identifier requires an indirect operator For example ant pe pb is same as int pa ant int pc Once declared though a pointer can usually be reassigned so that it points to an object of another type The mikroC for 8051 lets you reassign pointers without type casting but the compiler will warn you unless the pointer was o
193. ariables bg and border Like with struct and union declarations you can omit the tag if no further variables of this enum type are required Anonymous enum type enum black red green blue violet white color Enumeration Scope Enumeration tags share the same name space as structure and union tags Enumerators share the same name space as ordinary variable identifiers int blue 73 open a block enum colors black red green blue violet white enumerator blue 3 now hides outer declaration of int blue struct colors int i 3 ILLEGAL colors duplicate tag double red 2 ILLEGAL redefinition of red blue 37 back in int blue scope 150 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference VOID TYPE void is a special type indicating the absence of any value There are no objects of void instead void is used for deriving more complex types Void Functions Use the void keyword as a function return type if the function does not return a value void print temp char temp hod Dur Cp Temperature Qut Cp Lemp i Che 222 degres character hog Che Cpr Ts Use void as a function heading if the function does not take any parameters Alternatively you can just write empty parentheses main void same as main Generic Pointers Pointers can be declared
194. as Each variable may be explicitly assigned to a specific memory space by including a memory type specifi er in the declaration or implicitly assigned based on a memory model The following memory type specifiers can be used code data idata bdata xdata pdata Memory type specifiers can be included in svariable declaration For example char data data_buffer puts data buffer in data ram const char code txt ENTER PARAMETER puts text in program memory unsigned long xdata array 100 puts array in external memory float idata ibuffer puts ibuffer in idata raim MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 117 CHAPTER 4 8051 Specifics mikroC for 8051 If no memory type 15 specified for a variable the compiler locates the variable in the memory space determined by the memory model Small Compact or Large code data idata Description 118 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Program memory 64 KBytes accessed by opcode MOVC A DPTR The code memory type may be used for constants and func tions This memory 15 accessed using 16 bit addresses and may be on chip or external puts txt in program memory const char code txt ENTER PARAMETER Directly addressable internal data memory fastest access to variables 128 bytes This memory is directly accessed using 8 bit addresses and is the o
195. at the bottom of this page Example set the appropriate filter mask and message type value CANSPISetOperationMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPI module must be in config mode for mask settings Set all Hl mask bits to all filtered bits are relevant Note that 1 is just a cheaper way to write OxFFFFFFFF Complement will do the trick and fill it up with ones CANSPISetMask CANSPI MASK B1 1 CANSPI CONFIG MATCH MSG TYPE amp CANSPI CONFIG XTD MSG CANSPISetFilter Prototype void CANSPISetFilter char CAN FILTER long val char CAN CONFIG FLAGS Returns Description Configures message filter The parameter value is bit adjusted to the appropriate filter registers Parameters CAN FILTER CANSPI module filter number Valid values CANSPI FILTER constants see CANSPI constants val filter register value CAN CONFIG FLAGS selects type of message to filter Valid values CANSPI CONFIG ALL VALID MSG CANSPI CONFIG MATCH MSG TYPE amp CANSPI CONFIG STD MSG CANSPI CONFIG MATCH MSG TYPE amp CANSPI CONFIG XTD MSG see CANSPI constants MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 229 CHAPTER 6 Libraries mikroC for 8051 Requires CANSPI module must be in Config mode otherwise the function will be ignored See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be pr
196. ations where the mikroC for 8051 syntax expects a statement but the program does not need one For example a null statement is commonly used in empty loops for git ott body of this Joop is s null statement 5 7 202 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference SELECTION STATEMENTS Selection or flow control statements select one of alternative courses of action by testing certain values There are two types of selection statements if switch IF STATEMENT The if statement is used to implement a conditional statement The syntax of the if statement is if expression statementl else statement2 If expression evaluates to true statement1 executes If expression 1s false statement2 executes The expression must evaluate to an integral value other wise the condition is ill formed Parentheses around the expression are mandato ry The elise keyword is optional but no statements come between if and else Nested If statements Nested 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 statementl else if expression2 if expression3 statement2 else statement3 this belongs to if expression3 else statement4 this belongs to if expre
197. ators and to add an integral value to a pointer The result of addition is defined only if the pointer points to an element of an array and if the result is a pointer pointing to the same array or one element beyond it If a pointer is declared to point to type adding an integral value n to the pointer increments the pointer value by n sizeof type as long as the pointer remains within the legal range first element to one beyond the last element If type has a size of 10 bytes then adding 5 to a pointer to t ype advances the pointer 50 bytes in memory In case of the void type the size of a step is one byte For example int 10 array a containing 10 elements of type int int 0 pa is pointer to int pointing to a 0 pa 3 6 pat3 is a pointer pointing to a 3 so a 3 now equals 6 pat pa now points to the next element of array a arij There is no such element as one past the last element of course but the pointer 15 allowed to assume such value C guarantees that the result of addition is defined even when pointing to one element past array If points to the last array element P 11s legal 2 is undefined This allows you to write loops which access the array elements a sequence by means of incrementing pointer in the last iteration you will have the pointer pointing to one element past the array which is legal However applying an i
198. ble to assign to pci a const value by assigning to pi Similar rules applayed to the volatile modifier Note that both const and volatile can appear as modifiers to the same identifier CONSTANT EXPRESSIONS A constant expressions can be evaluated during translation rather that runtime and accordingly may be used any place that a constant may Constant expressions can consist only of the following literals enumeration constants simple constants no constant arrays or structures sizeof operators Constant expressions cannot contain any of the following operators unless the oper ators are contained within the operand of a sizeof operator assignment comma decrement function call increment Each constant expression can evaluate to a constant that 15 in the range of repre sentable values for its type Constant expression can be used anywhere a constant 15 legal 134 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference KEYWORDS Keywords are words reserved for special purposes and must not be used as normal identifier names Beside standard C keywords all relevant SFR are defined as global variables and represent reserved words that cannot be redefined for example 0 PCL etc Probe the Code Assistant for specific letters Ctrl Space in Editor or refer to Predefined Globals and Constants is an
199. body Use the break statement within loops to pass control to the first statement following the innermost switch rof while Or do block Break 15 commonly used in the switch statements to stop its execution upon the first positive match For example MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 207 CHAPTER 5 Language Reference mikroC for 8051 switch state case 0 Lo break case 1 Mid break case 2 Hi break default Message Invalid state Continue Statement The continue statement within loops is used to skip the cycle It passes control to the end of the innermost enclosing end brace belonging to a looping construct At that point the loop continuation condition is re evaluated This means that contin ue demands the next iteration if the loop continuation condition 1s true Specifically the continue statement within the loop will jump to the marked posi tion as it is shown below while do if val 0 continue if gt 0 continue continue jumps here continue jumps here while POP ssf sses 4 Li 8 gt continue continue jumps here GOTO STATEMENT The goto statement is used for unconditional jump to a local label for more infor mation on labels refer to Labeled Statements The syntax of the goto statement 15 goto label identifier This will transfer control to the location of a local label specified by label iden
200. building bricks in your projects Copy them entirely if you deem fit that s why we included them with the compiler Where to Start In case that you re a beginner in programming 8051 microcon trollers read carefully the 8051 Specifics chapter It might give you some useful pointers on 8051 constraints code portability and good programming practices If you are experienced in C programming you will probably want to consult mikroC Specifics first For language issues you can always refer to the comprehensive Language Reference A complete list of included libraries is available at mikroC Libraries If you are not very experienced in C programming don t panic mikroC 8051 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 mikroC for 8051 MIKROELEKTRONIKA ASSOCIATES LICENSE STATEMENT AND LIMITED WARRANTY IMPORTANT READ CAREFULLY This license statement and limited warranty constitute a legal agreement License Agreement between you either as an individual or a single entity and mikroElektronika mikroElektronika Associates for software product Software identified above including any software media and accompanying on line or printed docume
201. but can be declared several times assuming that the declarations are compatible When declaring a function the formal argument s identifier does not have to be specified but its type does This kind of declaration commonly known as the function prototype allows better control over argument number type checking and type conversions The name of a parameter in function prototype has its scope limited to the prototype This allows one parameter identifier to have different name in different declarations of the same function 182 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference Here are two prototypes of the same function int test const char declares function test int test const char p declares the same function test Function prototypes are very useful in documenting code For example the function Cf Init takes two parameters Control Port and Data Port The question is which is which The function prototype void lInit ohar otrlport char d taport makes it clear If a header file contains function prototypes the user can read that file to get the information needed for writing programs that call these functions If a prototype parameter includes an identifier then the indentifier 1s only used for error checking Function Definition Function definition consists of its declaration and function body The function body is techni
202. 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 28760 module should be properly cofigured by the means ofSpi Ethernet Init routine Ethernet module has to be initialized See Spi Ethernet Init Example Ethernet Enableib pi Ethernet CRC api Ethernet UNICAST nable checking and Unicast traffic 338 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 CHAPTER 6 Libraries Spi Ethernet Disable Prototype void Spi Ethernet Disable unsigned char disFlt Returns Nothing Description This is MAC module routine This routine disables appropriate network traffic on the ENC28J60 module by the means of it s receive filters unicast multicast broadcast crc Specific type of network traffic will be disabled if a corresponding bit of this rou tine s input parameter is set Therefore more than one type of net work 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 disrit network traffic receive filter flags Each bit corre
203. c Init function See the Library Example 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 408 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries External dependencies of T6963C Graphic LCD Library The following variables must be defined in all projects using T6963C Graphic LCD library extern unsigned char sfr T6963C dataPort extern unsigned char afr GLELPOZLT extern sbit TO963L ctrlwr extern sbit extern sbit Cre led extern sbit CTE rot Description T6963C Data Port T6963C Control Port Write signal Read signal Command Data signal Reset signal MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Example unsigned char sfr T6953C dataPort at PO unsigned char sfr 69630 DLELPOFTL at Pi sbit TovGsC ctrlwr at Pl B23 sbit TOSESL HE PI BI sbit at 007 sbit 69630 eCcrlrec 21 847 409 CHAPTER 6 Libraries mikroC for 8051 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 T6963
204. cally a block a sequence of local definitions and statements enclosed with in braces All variables declared within function body are local to the function i e they have function scope The function itself can be defined only within the file scope which means that func tion declarations cannot be nested To return the function result use the return statement The statement return 1n func tions of the void type cannot have a parameter in fact the return statement can be omitted altogether if it 1s the last statement in the function body Here is a sample function definition function max returns greater one of its 2 arguments int max int x int return x gt y x y Here is a sample function which depends on side effects rather than return value MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 183 CHAPTER 5 Language Reference mikroC for 8051 function converts Descartes coordinates x y to polar r fi Finclude void polar double x double y double double 1 x xfi x 0 amp amp y 0 0 atan2 y x return this line can be omitted Functions reentrancy Functions reentrancy is allowed Remember that the 8051 has stack and memory limitations which can varies greatly between MCUs FUNCTION CALLS AND ARGUMENT CONVERSIONS Function Calls A function is called with actual arguments placed
205. can be given for each identifier in a translation unit declared with internal linkage An external definition is an external declaration that defines an object or a function and also allocates a storage If an identifier declared with external linkage is used an expression other than as part of the operand of sizeof then exactly one external definition of that identifier must be somewhere in the entire program STORAGE CLASSES Associating identifiers with objects requires each identifier to have at least two attributes storage class and type sometimes referred to as data type The mikroC for 8051 compiler deduces these attributes from implicit or explicit declarations in the source code A storage class dictates the location data segment register heap or stack of object and its duration or lifetime the entire running time of the program or during exe cution of some blocks of code A storage class can be established by the syntax of a declaration by its placement in the source code or by both of these factors storage class type identifier The storage class specifiers in the mikroC for 8051 are auto register static extern Auto The auto modifer is used to define that a local variable has a local duration This 15 the default for local variables and is rarely used auto can not be used with globals See also Functions 176 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5
206. can launch it from the drop down menu Tools UDP Terminal a UDP Communication Terminal 3 Settings IP Address 92 168 20 60 Connect Fort fi 0001 Send mikroElektronika E LIAE i Append Send as typing LF Send as number mikraE lektronika Receive ASCII 64 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Graphic LCD Bitmap Editor The mikroC for 8051 includes the Graphic LCD Bitmap Editor Output 15 the mikroC for 8051 compatible code You can launch it from the drop down menu Tools GLCD Bitmap Editor mikraElektronika Graphic LCD Bitmap generator 50108 T6963 Nokia3110 File loaded truck bmp Picture preview 128x64 pix bw Load Picture Create CODE li GLCD Size f controller 740x128 not imp vet 126x125 not et 128x64 50108 imp eri ff 77 GLCD Picture name truck bmp GLCD Model KS8188 128x64 Copy CODE to Clipboard z m mikroPASCAL code mikroBASIC code unsigned char const truck bmp 1824 o B 3 miktoC cod Eo H rol code A Be al 8 P i1 8 e Fh a H 8 i rk ver 2 0 1 27012005 System status Win NT li
207. ce Por example SOIL Uart Bead fakes the pointer error variate so it can change the value of an actual argument SOTE Uart Bead amp error The following code would be wrong you would pass the value of error variable to the function cort Vart Read error Argument Conversions If a function prototype has not been previously declared the mikroC for 8051 con verts integral arguments to a function call according to the integral widening expan sion rules described in Standard Conversions If a function prototype is in scope the mikroC for 8051 converts the passed argument to the type of the declared param eter according to the same conversion rules as in assignment statements If a prototype is present the number of arguments must match The types need to be compatible only to the extent that an assignment can legally convert them The user can always use an explicit cast to convert an argument to a type that is acceptable to a function prototype Note If the function prototype does not match the actual function definition the mikroC for 8051 will detect this if and only 1f that definition is in the same compi lation unit as the prototype If you create a library of routines with the correspon ding header file of prototypes consider including that header file when you compile the library so that any discrepancies between the prototypes and actual definitions will be detected The compiler is also able
208. ching feio Examples rou tine te matches strings routine route MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 73 CHAPTER 2 Environment mikroC for 8051 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 opening parenthesis First subexpression has number 1 Examples int 8 10 matches strings which contain 8 9 or 10 instances of the int routi 0 9 a e matches routi0e routile routine routinne routinnne etc Metacharacters Backreferences Metacharacters 1 through 9 are interpreted as backreferences matches previ ously matched subexpression Examples 1 matches aaaa and cc 1 matches abab and 123123 1 d M matches 13 in double quotes or 4 in single quotes or 77 without quotes etc 74 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment MIKROC FOR 8051 COMMAND LINE OPTIONS Usage mikroC8051 opts opts infile opts opts Infile can be of c and mcl type The following parameters and some more see manual are valid MCU for which compilation will be done FO Set oscillator SP Add directory to the search path list 1P Add directory to the include search list N Output fi
209. communication see Spi Led8 Config routines Example 47 Write character i at row 2 column 3 000 016185 2 7277 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 379 CHAPTER 6 Libraries mikroC for 8051 Spi Lcd8 Chr Prototype void Spi Lcd8 Chr CP char out char Description Prints character on LCD at current cursor position Both variables and literals can be passed as character Parameters out char character to be written Requires LCD needs to be initialized for SPI communication see Spi Led8 Config routines Example Print at current cursor position Write character e at current cursor position 16809 Chr to Spi Prototype void Spi Lcd8 Cmd char out char Description Sends command to LCD Parameters out char command to be sent Note Predefined constants can be passed to the function see Available LCD Commands Requires LCD needs to be initialized for SPI communication see Spi Led8 Config routines Example Clear LCD display Spi Lcd8 Cmd LCD CLEAR 380 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Available LCD Commands LCD_RETURN_HOME Return cursor to home position returns a shifted dis play to its original position Display data RAM 15 unaf fected MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WO
210. compiler can recognize The pars er separates tokens from the input stream by creating the longest token possible using the input characters in a left to right scan The mikroC for 8051 recognizes the following kinds of tokens keywords identifiers constants operators punctuators also known as separators Tokens be concatenated pasted by means of the preprocessor operator See the Preprocessor Operators for details Token Extraction Example Here is an example of token extraction Take a look at the following example code sequence inter a b First note that inter would be parsed as a single identifier rather than as the key word int followed by the identifier er The programmer who has written the code might have intended to write inter a b but it wouldn t work that way The compiler would parse it into the seven following tokens inter variable identifier assignment operator a variable identifier P postincrement operator addition op rator le variable identifier H 27 statement terminator Note that parses as the longest token possible followed by According to the operator precedence rules our code sequence is actually inter b 126 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference CONSTANTS Constants or literals are tokens representing fixed numeric o
211. convention argu ment order arguments type or return type is different are incompatible with each other Assign an address to a Function Pointer It s quite easy to assign the address of a function to a function pointer Simply take the name of a suitable and known function Using the address operator amp infront of the function s name 15 optional Assign an address to the function pointer int DoIt float char D char return atbto 1 pt2Function amp DoIt assignment 156 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference Example int addC char x char y return x y int subC char x char y return x y int mulC char x char y return x y int divC char x char y return x y int modC char x char y return x y array of pointer to functions that receive two chars and returns int int arrpt har char adac subC mulC divC modcG int res char i void main for 1 0 1 lt 5 1 res arrpf i 10 20 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 157 CHAPTER 5 Language Reference mikroC for 8051 POINTER ARITHMETIC Pointer arithmetic in the mikroC for 8051 is limited to assigning one pointer to another comparing two pointers comparing pointer to zero adding subtracting pointer and an integer value subtracting two
212. coordinate of vertical line Valid values 0 127 color color parameter Valid values 0 2 Parameter color determines the line color 0 white 1 black and 2 inverts each dot pee GLCD needs to be initialized for SPI communication see routines Example Draw a vertical line between dots 10 5 and 121 42 Gled V Spi Glcd H Line Prototype void Spi Glcd H Start char char y pos Ghar color Returns Nothing Description Draws a horizontal line on GLCD Parameters x start X coordinate of the line start Valid values 0 127 x end X coordinate of the line end Valid values 0 127 y pos y coordinate of horizontal line Valid values 0 63 color color parameter Valid values 0 2 The parameter coior determines the line color 0 white 1 black and 2 inverts each dot pee GLCD needs to be initialized for SPI communication see Iani Gled Init routines Example Draw a horizontal line between dots 10 20 and 50 20 spi Gled H Lane tld 30 lt 0 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 361 CHAPTER 6 Libraries mikroC for 8051 Spi Glcd Rectangle Prototype void Spi Glcd Rectangle char x upper left char y upper char x bottom right char y bottom Tight char color Description Draws a rectangle on GLCD Parameters x upper left X coordinate of the upper left rectangle corner Valid va
213. cs Keyboard shortcuts File Toolbar Managing Source Files 14 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment EDIT MENU OPTIONS Undo Redo Shifk Ctrl 2 Cut Paste Delete Select All Find Ctrl F 4 Find Next Find Previous Shift F3 3 Replace X FindInFiles Alt F3 Goto Line Ctrl amp Advanced k MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 15 CHAPTER 2 Environment mikroC for 8051 Find text in active editor ccm Find next occurence of text in active editor a3 Find previous occurence of text in active editor Jg Replace Replace text in active editor Find text in current file in all opened files or in FindIn Files files from desired folder Goto Line Ctrl g Goto to the desired line in active editor Advanced Code Editor options Comment selected code or put single line com Comment ment if there is selection Uncomment selected code or remove single line 1 1 Uncomment Shifk Ctri comment if there is no selection Indent shift ctri 1 Indent selected code EE Outdent utdent Shift CErl L Outdent selected code Changes selected text case to lowercase Aa Lowercase Lowercase Aa Lowercase
214. ctive such directive will not be recognized by the preprocessor Any occurrences of the macro identifier found within literal strings character constants or comments in the source code will not be expanded A macro won t be expanded during its own expansion 50 define MACRO MACRO won t expand indefinitely Here is an example Here are some simple macros ERR MSG Out of range define EVERLOOP for which we could use like this maini 1 EVERLOOP if error Lcd Out Cp ERR MSG break Attempting to redefine an already defined macro identifier will result in a warning unless a new definition is exactly the same token by token definition as the existing one The preferred strategy when definitions might exist in other header files is as follows ifndef BLOCK SIZE define BLOCK SIZE 512 dendif The middle line is bypassed if BLOCK 512518 currently defined if BLOCK SIZE 15 not currently defined the middle line 15 invoked to define it 212 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference Macros with Parameters The following syntax is used to define a macro with parameters macro igdentifier carg Jist gt token sequence gt Note that there can be no whitespace between macro identifier and The optional arg list 15 a sequence of identifiers separated by commas like the argu
215. d Scope 136 Identifier Examples 136 PONCO usted Hace ee 137 Brackets MEE 137 Parentheses 2 Ne 137 today dence bens 138 eonun 138 snis m 138 GOON sarrerea 139 Asterisk Pointer Declaration 139 Equal SIGW P oad 139 Pound Sign Preprocessor Directive 140 CONCODIS 140 Qoo D Pr m 140 Objects and Declarations 141 22252555445 nese 141 sU R 142 Scope Visibility 142 vis 142 VISIIDI cee oes ew eee a Gee een PEG oe 142 Spaces 143 Bio ee Gere eee oes ene ee ee 144 Statie ae e
216. d file to the active project Remove selected file from the project Build the active project Run mikroElektronika s Flash programmer For details about adding and removing files from project see Add Remove Files from Project Related topics Project Settings Project Menu Options File Menu Options Project Toolbar Build Toolbar Add Remove Files from Project 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 Memory Model Select the desired memory model Project Settings Eg Device 479959253 Value O08 000000 gt Small Large Compact Related topics Memory Model Project Manager SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 49 CHAPTER 2 50 Environment mikroC for 8051 LIBRARY MANAGER Library Manager enables simple handling libraries being used in a project Library Manager window lists all libraries extencion mcl which are instantly stored in the compiler Uses folder The desirable library is added to the project by selecting check box next to the library name In order to have all library functions accessible simply press the button Check All and all libraries will be selected In case none library is needed in a project press the button C
217. dd the Library Alias and Library Name at the end of the definition file for example pragma SetLib Example Library _ Lib Example 8 Add Library to mlk file for each MCU that you want to use with your library 9 Click Refresh button in Library Manager Multiple Library Versions Library Alias represents unique name that is linked to corresponding Library mc1 file For example UART library for AT89S8253 1s different from UART library for AT89S4051 MCU Therefore two different UART Library versions were made see mlk files for these two MCUs Note that these two libraries have the same Library Alias UART in both mix files This approach enables you to have identical repre sentation of UART library for both MCUS in Library Manager Related topics Library Manager Project Manager Managing Source Files MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 95 CHAPTER 2 Environment mikroC for 8051 96 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER mikroC for 8051 Specifics The following topics cover the specifics of mikroC compiler ANSI Standard Issues Predefined Globals and Constants Accessing Individual Bits Interrupts 8051 Pointers Linker Directives Built in Routines Code Optimization 97 CHAPTER 3 Specifics mikroC for 8051 ANSI STANDARD ISSUES Divergence from the ANSI C Standard Tentative declaration are not supported Function
218. degrees Note Return value range 1000 1000 Example int res res 196 result is 193 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 471 mikroC for 8051 If you are experiencing problems with any of our products or you just want addi tional information please let us know Technical Support for the compiler If you are experiencing any trouble with mikroC for 8051 please do not hesitate to contact us it is in our mutual interest to solve these issues Discount for schools and universities mikroElektronika offers a special discount for educational institutions If you would like to purchase mikroBasic for purely educational purposes please con tact us Problems with transport or delivery If you want to report a delay in delivery or any other problem concerning distri bution of our products please use the link given below Would you like to become mikroElektronika s distributor We in mikroElektronika are looking forward to new partnerships If you would like to help us by becoming distributor of our products please let us know Other If you have any other question comment or a business proposal please contact us mikroElektronika Visegradska 1A 11000 Belgrade EUROPE Phone 381 11 36 28 830 Fax 381 11 36 28 831 E mail office mikroe com Support support mikroe com Web www mikroe com 472 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EM
219. dene Gee 154 Pointer Declarations 154 Null POIDIBES a duh nnd md xd PE 155 PUNCIOMN 2224 so dete ee oe bea a aes eed 156 Pointer 158 Arrays and lt 5 158 Assignment and Comparison 159 Pointer Addition 160 Pointer Subtraction 161 SUGGS e ROG EISE Boe et awe a Da SS eee x 161 Structure Declaration and Initialization 162 Incomplete Declarations 163 Untagged Structures and Typedefs 163 Working with Structures 164 ASSIGNING 3 eta be deed ird di dete ENO ap cede dolo etie d 164 Of eus aa 164 Structures lt 164 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Table of Contents mikroC for 8051 Structure Member Access 165 Accessing Nested Structures 166 Structure Uniqueness 166 NOMS ew ee ne he ee ee ee Pe ee 167 U
220. double variant are considered to be floating point types The mikroC for 805175 implementation of an ANSI Standard considers all three to be the same type Floating point in the mikroC for 8051 is implemented using the Microchip 575 32 bit format IEEE 754 compliant An overview of the floating point types is shown in the table below 1 5 1045 3 4 1938 1 5 1045 3 4 1038 45 38 wee long double 148 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference ENUMERATIONS An enumeration data type is used for representing an abstract discreet set of values with appropriate symbolic names Enumeration Declaration Enumeration is declared like this enum tag enumeration list Here tag is an optional name of the enumeration enumeration list 15 comma delimited list of discreet values enumerators or enumeration constants Each enu merator 15 assigned a fixed integral value In the absence of explicit initializers the first enumerator 15 set to zero and the value of each succeeding enumerator is set to a value of its predecessor increased by one Variables of the enum type are declared the same as variables of any other type For example the following declaration enum colors black red green blue violet white c establishes a unique integral type enum colors variable c of this type and set of enume
221. e a 3 14 For more information see the Pointers Equal Sign Equal sign separates variable declarations from initialization lists inb test 5 D 1 2 2 4 513 inb x 5 Equal sign is also used as an assignment operator in expressions MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 139 CHAPTER 5 Language Reference mikroC for 8051 int a D a b For more information see Assignment Operators Pound Sign Preprocessor Directive Pound sign indicates a preprocessor directive when it occurs as the first non whitespace character on a line It signifies a compiler action not necessarily associ ated with a code generation See the Preprocessor Directives for more information and are also used as operators to perform token replacement and merging dur ing the preprocessor scanning phase See the Preprocessor Operators CONCEPTS This section covers some basic concepts of language essential for understanding of how C programs work First we need to establish the following terms that will be used throughout the help Objects and lvalues Scope and Visibility Name Spaces Duration OBJECTS An object is a specific region of memory that can hold a fixed or variable value or set of values This use of a term object is different from the same term used in object oriented languages which 15 more general Our definiton of the word would
222. e expression has a qualified or unqualified version of structure or union type compatible with the type of expression2 expressionl and expression are pointers to qualified or unqualified versions of compatible types and the type pointed to by left has all qualifiers of the type pointed to by right Either expressionl expression is a pointer to an object or incomplete type and the other 15 a pointer to a qualified or unqualified version of void The type pointed to by left has all qualifiers of the type pointed to by right expressionl is a pointer and expression 15 a null pointer constant SIZEOF OPERATOR The prefix unary operator sizeof returns an integer constant that represents the size of memory space in bytes used by its operand determined by its type with some exceptions The operator sizeof can take either a type identifier or an unary expression as an operand You cannot use sizeof with expressions of function type incomplete types parenthesized names of such types or with lvalue that designates a bit field object 198 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference Sizeof Applied to Expression If applied to expression the size of an operand is determined without evaluating the expression and therefore without side effects The result of the operation will be the size of the type of the expression s result Sizeof Appli
223. e Breakpoints Window List locates the breakpoint Run to cursor Execute all instructions between the current instruction and cursor position Execute the current C single or multi cycle instruction SDN then halt If the instruction is a routine call enter the routine and halt at the first instruction following the call Step Over Execute the current C single or multi cycle instruction then halt Step Out Execute all remaining instructions in the current routine return and then halt Related topics Run Menu Debug Toolbar 94 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment CREATING NEW LIBRARY mikroC for 8051 allows you to create your own libraries In order to create a library in mikroC for 8051 follow the steps bellow 1 Create a new C source file see Managing Source Files 2 Save the file in the compiler s Uses folder DriveName Program FilesMMikroelektronikaNmikroC 8051 lab Example c 3 Write a code for your library and save it 4 Add Lib Exampie c file in some project see Project Manager Recompile the project Compiled file Lib Example mcl should appear in mikroc 8051 Uses folder 6 Open the definition file for the MCU that you want to use This file is placed in the compiler s Defs folder DriveName Program FilesMMikroelektronikaNmikroC 8051 Defs and it is named MCU NAME mlk for example AT89S8253 mlk 7 A
224. e you can save the layout by typing the name for the layout and pressing the Save Layout Icon l3 To set the layout select the desired layout from the layout list and click the Set Layout Icon remove the layout from the drop down list select the desired layout from the list and click the Delete Layout Icon 1 Debug Layout Default Layout Code Layout Debug Layout layout Auto Hide Auto Hide enables you to see more of your code at one time by minimizing tool windows along the edges of the IDE when not in use Click the window you want to keep visible to give it focus Click the Pushpin Icon zz on the title bar of the window MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 39 CHAPTER 2 Environment mikroC for 8051 Project Manager T 59 TEST 09 8 festProjectameproj B Sources M Secsnderosecte Files DO CO Project lewel defres Insoe Files C3 Orc Fies O Other Files aad When auto hidden window loses focus it automatically slides back to its tab on the edge of the IDE While a window 1s auto hidden its name and icon are visible on a tab at the edge of the IDE To display an auto hidden window move your point er over the tab The window slides back into view and 1s ready for use 40 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environ
225. e as i 3 i e afi 1 3 Lr wd 04 Jf Game 2 2 B 0 Ali 2 0 Assignment and Comparison The simple assignment operator can be used to assign value of one pointer to another if they are of the same type If they are of different types you must use a typecast operator Explicit type conversion is not necessary if one of the pointers is generic of the void type Assigning the integer constant 0 to a pointer assigns a null pointer value to it Two pointers pointing to the same array may be compared by using relational oper ators lt lt gt and gt Results of these operations are the same as if they were used on subscript values of array elements in question if pa pb won t be executed as 4 is not equal to 2 1 pa gt pb will be executed as 4 is greater than 2 You can also compare pointers to zero value testing in that way if the pointer actu ally points to anything All pointers can be successfully tested for equality or inequality to null MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 159 CHAPTER 5 Language Reference mikroC for 8051 if 0 if gb t 0 Note Comparing pointers pointing to different objects arrays can be performed at programmer s own responsibility a precise overview of data s physical storage is required Pointer Addition You can use oper
226. ead PortA Expander Read PortB Expander Read PortAB Expander Write PortA Expander Write PortB Expander Write PortAB Expander Set DirectionPortA Expander Set DirectionPortB Expander Set DirectionPortAB 294 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Expander Set PullUpsPortA Expander Set PullUpsPortB Expander Set PullUpsPortAB Expander Init Prototype void Expander Init char ModuleAddress Description 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 bottom of this page Requires SPExpandercs and SPExpanderRST variables must be defined before using this function SPI module needs to be initialized See Spi Init and Spi Init Advanced routines Example port expander pinout definition sbit SPExpanderRST at 1 0 sbit SPExpanderCS at 1 1 Spi initialize SPI module Expander Init 0 initialize port expander MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 285 CHAPTER 6 Libraries mikroC for 8051 Expander Read Byte Prototype char awa Read Byte char ModuleAddress char RegAddress Description The function
227. eader file at that point in the source code The placement of include can there fore influence the scope and duration of any identifiers in the included file The difference between these two formats lies in searching algorithm employed in trying to locate the include file If the include directive 15 used with the lt header name gt version the search 15 made successively in each of the following locations in this particular order 214 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference 1 the mikroC for 8051 installation folder gt include folder 2 user s custom search paths The header name version specifies a user supplied include file the mikroC for 8051 will look for the header file in the following locations in this particular order 1 the project folder folder which contains the project file ppc 2 the mikroC for 8051 installation folder include folder 3 user s custom search paths Explicit Path By placing an explicit path in header name only that directory will be searched For example Tinoclude FilasVtest h Note There is also a third version of the include directive rarely used which assumes that neither nor appear as the first non whitespace character following Finclude rinplude macro identi tier It assumes that macro definition that will expand macro identifier into a valid delim ited header name wi
228. eak break break break break break break break break break break break break break break A pA eypad4x4 Lj se O Oo D o 0 a oo B Pressed key differs from previous Pressed key is same as previous Print key ASCII value on LCD yr If gounter overflow 2 2 Transform counter value to string Display counter value on LCD 262 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries HW Connection GC8S68 1V LCD 2X16 6 3 4x4 Keypad connection scheme MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 263 CHAPTER 6 Libraries mikroC for 8051 LCD LIBRARY The mikroC for 8051 provides a library for communication with LCDs with HD44780 compliant controllers through the 4 bit interface An example of LCD connections 1s 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 Description Example Library extern sbit LCD RS Register Select line sbit LCD RS at P2 B0 extern sbit LCD EN Enable line sbit LCD EN at 2 1 Library Routines Led Init Led Out Led Led Chr Led Chr Cp Led Cmd 264 MIKROELEKTRONIKA S
229. ecked before the first entry into the block state ment 1s executed repeatedly until the value of condition expression is false After each iteration of the loop increment expression increments a loop count er Consequently i is functionally the same as i All expressions are optional If condition expression is left out it is assumed to be always true Thus empty for statement is commonly used to create an end less loop in C 206 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference for statement The only way to break out of this loop is by means of the break statement Here 15 an example of calculating scalar product of two vectors using the for state ment for s 0 i 0 1 n i s 14 Hil There is another way to do this tor S e D 4 14 n a Hi A dil X4 P valid but ugly but it 1s considered a bad programming style Although legal calculating the sum should not be a part of the incrementing expression because it 1s not in the service of loop routine Note that null statement 15 used for the loop body JUMP STATEMENTS The jump statement when executed transfers control unconditionally There are four such statements in the mikroC for 8051 break continue goto return BREAK AND CONTINUE STATEMENTS Break Statement Sometimes it 15 necessary to stop the loop within its
230. ect the left side of GLCD Glod Set 2160610 SPI 5 0 410 Spi Glcd Set Page Prototype void Spi Glcd Set Page char page Description Selects page of GLCD Parameters page page number Valid values 0 7 Note For side x axis and page layout explanation see schematic at the bottom of this page Requires GLCD needs to be initialized for SPI communication see Spi Init routines Gled Set Page s MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 224 CHAPTER 6 Libraries mikroC for 8051 Spi Glcd Set X Prototype Description Sets x axis position to pos dots from the left border of GLCD within the selected side Parameters 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 Requires GLCD needs to be initialized for SPI communication see Spi Init routines Spi Glcd Set X 25 Spi Glcd Read Data One byte from GLCD memory Description Reads data from the current location of GLCD memory and moves to the next location Requires GLCD needs to be initialized for SPI communication see Spi Init routines GLCD side x axis position and page should be set first See the functions Spi Gled Set Side Spi Gled Set X and Spi Gled Set Page Example char data Spi Gled Bead Data 358 MIKROELEKT
231. ed In the absence of any overriding suffix es the data type of an octal constant is derived from its value according to the rules presented above For example 0777 will be treated as int FLOATING POINT CONSTANTS A floating point constant consists of Decimal integer Decimal point Decimal fraction e or and a signed integer exponent optional Type suffix or F or 1 optional Either decimal integer or decimal fraction but not both can be omitted Either dec imal point or letter e or with a signed integer exponent but not both can be omitted These rules allow conventional and scientific exponent notations Negative floating constants are taken as positive constants with an unary operator minus prefixed The mikroC for 8051 limits floating point constants to the range 1 17549435082 10 38 6 80564774407 1038 Here are some examples 0 0 0 ee yy 122 23 45 23 45 10 6 Jf 2 0 10 3 3ET10 ff 3 0 20410 09E34 0 09 10734 The mikroC for 8051 floating point constants are of the type doubie Note that the mikroC for 8051 s implementation of ANSI Standard considers float and double together with the long double variant to be the same type MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 129 CHAPTER 5 Language Reference mikroC for 8051 CHARACTER CONSTANTS A character constant is one or more characters enclos
232. ed before using this function Example 7T6963CGLCD unsigned char pointer to unsigned char pointer to sbit TO X530 sbit TOOG sbit CD command data signal sbit 5952 init display for 240 pixel width 128 pixel height and 8 bits character width Teves 1inlL 240 125 O Jj pinout definition sfr T6963C dataPort at PO DATA BUS port sfr TESEGL at Fi CONIROL port ctrlwr at P1 B2 WR write signal ctrlrd at 1 1 RD read signal at 1 0 Olrirst at RST reset signal MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 411 CHAPTER 6 Libraries mikroC for 8051 T6963C WriteData Prototype void T6963C WriteData unsigned char mydata Description Writes data to T6963C controller Parameters nydata data to be written Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine T6963C WriteData AddrL T6963C WriteCommand Prototype void T6963C WriteCommand unsigned char mydata Description Writes command to T6963C controller Parameters nydata command to be written Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine 412 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries T6963C SetPtr Protot
233. ed in both threads It 1s not recommended to use function call from interrupt In case of doing that take care of stack depth Interrupt Priority Level 8051 MCUs has possibilty to assign different priority level trough setting appropri ate values to coresponding SFRs You should also assign ISR same priority level by ilevel keyword followed by interrupt priority number Available interrupt priority levels are 0 default 1 2 and 3 void TimerOISR void org 0 000 ilevel 2 set 015 to be ISR for Timer 0 Overflow priority level 2 Related topics ANSI standard issues MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 101 CHAPTER 3 Specifics mikroC for 8051 LINKER DIRECTIVES The mikroC uses an internal algorithm to distribute objects within memory If you need to have a variable or routine at specific predefined address use the linker direc tives absolute and org Directive absolute Directive absolute specifies the starting address in RAM for a variable If the vari able is multi byte higher bytes will be stored at the consecutive locations Directive absolute 1s appended to declaration of a variable short x absolute 0x22 Variable x will occupy 1 byte at address 0x22 int y absolute 0x23 Variable y will occupy 2 bytes at addresses 0x23 and 0x24 Be careful when using the absolute directive as you may overlap two variables by accident For example char i absolute 0
234. ed in single quotes such as Ce or n In the mikroC for 8051 single character constants are of the unsigned int type Multi character constants are referred to as string constants or string literals For more information refer to String Constants Escape Sequences A backslash character 15 used to introduce an escape sequence which allows a visual representation of certain nongraphic characters One of the most common escape constants is the newline character A backslash is used with octal or hexadecimal numbers to represent an ASCII sym bol or control code corresponding to that value for example for the ques tion mark Any value within legal range for data type char 0 to 0xrr for the mikroC for 8051 can be used Larger numbers will generate the compiler error Out of range For example the octal number 777 1s larger than the maximum value allowed 377 and will generate an error The first nonoctal or nonhexadecimal character encountered in an octal or hexadecimal escape sequence marks the end of the sequence Note You must use the sequence to represent an ASCII backslash as used in operating system paths The following table shows the available escape sequences 130 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference DENN NEL NN MN DENN GN LEE EMEN OA Nee 0 o0 MD CR Caine Ret
235. ed to Type If applied to a type identifier sizeof returns the size of the specified type The unit for type size is sizeof char Which is equivalent to one byte The operation size of char gives the result 1 whether char is signed or unsigned Thus sizeof char returns 1 sizeof int returns 2 sizeof unsigned long returns 4 sizeof float returns 4 When the operand is a non parameter of array type the result 1s the total number of bytes in the array in other words an array name is not converted to a pointer type INL 9 sizeof a 1 1 sizeof int 2 sizeof a Y Ip toizeor int 20 H U e To get the number of elements in an array int num elem 1 3 If the operand is a parameter declared as array type or function type sizeof gives the size of the pointer When applied to structures and unions sizeof gives the total number of bytes including any padding The operator sizeof cannot be applied to a function MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 199 CHAPTER 5 Language Reference mikroC for 8051 EXPRESSIONS Expression is a sequence of operators operands and punctuators that specifies a computation Formally expressions are defined recursively subexpressions can be nested without formal limit However the compiler will report an out of memory error if it can t compile an expression that is too comp
236. ed to group expressions isolate conditional expressions and indicate func tion calls and function parameters d c b override normal precedence if 7 FIX essential with conditional statement func Iunctios Call no aros y void func2 ant function declaration with parameters Parentheses are recommended in macro definitions to avoid potential precedence problems during an expansion define CUBE x x x For more information refer to Operators Precedence And Associativity and Expressions MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 137 CHAPTER 5 Language Reference mikroC for 8051 Braces Braces indicate the start and end of a compound statement if z Closing brace serves as a terminator for the compound statement so a semicolon 1s not required after except in structure declarations Sometimes the semicolon can be illegal as in if statement L 2x 14 illegal semicolon else Uo For more information refer to the Compound Statements Comma Comma separates the elements of a function argument list void func int n float f char ch Comma is also used as an operator in comma expressions Mixing two uses of comma is legal but you must use parentheses to distinguish them Note that expl exp2 evalutates both but is equal to the second fn i 72 call func with two args
237. ed to simplify handling of the underlying hardware lt 282760 It works with any 8051 MCU with integrated SPI and more than 4 Kb ROM memory SPI Ethernet library supports 4 protocol ARP requests ICMP echo requests UDP requests TCP requests no stack no packet reconstruction packet fragmentation is NOT supported Note For advanced users there are header files eth enc28j60LibDef h and eth enc28j60LibPrivate h in Uses folder of the compiler with description of all routines and global variables relevant to the user implemented in the SPI Ethernet Library Note The appropriate hardware SPI module must be initialized before using any of the SPI Ethernet library routines Refer to Spi Library 334 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 CHAPTER 6 Libraries External dependencies of SPI Ethernet Library The following vari ables must be defined in all projects using SPI Ethernet Library Description extern sfr sbit ENC28J60 chip Sep Ethernet Coz select pin extern sfr sbit ENC28J60 reset spi Ethernet RDT pun The following routines must be defined in all project using SPI Ethernet Library unsigned int USPITLE unsigned char remoteHost unsigned int remotePort unsigned int localPort unsigned int reqLength unsigned int Erhernet User uDE unsigned char remoteHost unsigned int re
238. ee Locate declaration in code 46 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment ROUTINE LIST Routine list diplays list of routines and enables filtering routines by name Routine list window be accessed by pressing Ctrl L You can jump to a desired routine by double clicking on it MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 47 CHAPTER 2 Environment mikroC for 8051 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 15 performed by double click on the desired project in the Project Manager Project Manager 5 95 28 E MFirstProject mcproj ic SOURCES FirstProject c 71 Header Files ca Binaries 7 Project level defines 7j Image Files Output Files FirstProject hex FirstProject asm sm FirstProject 73 Other Files Following options are available in the Project Manager Save project Group Open project group Close the active project Close project group B Add project to the project group 48 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment B Remove project from the project group Ad
239. elational and arithmetic operators was designated in such a way to allow complex expressions without parentheses to have an expected mean ing Q gt Le cae reads as foe se 101 lt 7971 1 reads 1 b f my Logical AND ss returns 1 only if both expressions evaluate to be nonzero otherwise returns 0 If the first expression evaluates to false the second expression will not be evaluated For example a gt DER d reads as a gt b amp amp c d if im gt b is false 0 c lt will not be evaluated Logical OR returns 1 if either of expression evaluates to be nonzero otherwise returns 0 If the first expression evaluates to true the second expression 1s not eval uated For example a amp amp b c amp amp d reads as b amp amp d if a b is true 1 c amp amp d will not be evaluated Logical Expressions and Side Effects General rule regarding complex logical expressions is that the evaluation of consec utive logical operands stops at the very moment the final result is known For exam ple if we have an expression a 55 b 55 c where a is false 0 then operands gt and c will not be evaluated This is very important if are expressions as their possible side effects will not take place MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTI
240. ernet Enable Prototype void Spi Ethernet Enable unsigned char enFlt to the appropriate network traffic receive filter Description This is MAC module routine This routine enables appropriate network traffic on the 28760 module by the means of it s receive filters unicast multicast broadcast crc Specific type of network traffic will be enabled if a corresponding bit of this rou tine s input parameter is set Therefore more than one type of net work traffic can be enabled at the same time For this purpose predefined library constants see the table below can s ORed to form appropriate input value Parameters enF1t network traffic receive filter flags Each bit corresponds MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 337 CHAPTER 6 Libraries mikroC for 8051 M Description Predefined library const MAC Broadcast traffic receive fil ter flag When set MAC broadcast Spi Ethernet BROADCAST traffic will be enabled MAC Multicast traffic receive filter flag When set MAC multicast Spi Ethernet MULTICAST traffic will be enabled CRC check flag When set packets with invalid CRC field will be dis Spi Ethernet CRC carded MAC Unicast traffic receive filter flag When set MAC unicast traffic Spi Ethernet UNICAST will be enabled Note Advance filtering available in the amp c28560 module such as Pattern Match Magic Packet and Hash Table can not be enabled
241. ernet putByte data put an byte into ENC28J60 buffer Spi Ethernet putBytes Prototype void Spi Ethernet putBytes unsigned char ptr unsigned char n Description This is MAC module routine It stores requested number of bytes into ENC28J60 RAM starting from current ENC28J60 write pointer EWRPT location Parameters ptr RAM buffer containing bytes to be written into xNc284760 n number of bytes to be written Requires Ethernet module has to be initialized See Spi Ethernet Init Example char buffer mikroElektronika Spi Ethernet putBytes buffer 16 put an RAM array into ENC28J60 buffer MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 34 CHAPTER 6 Libraries mikroC for 8051 Spi Ethernet putConstBytes Prototype void Spi Ethernet putConstBytes const unsigned char ptr unsigned char n Returns Description This is MAC module routine It stores requested number of const bytes into zNc28760 RAM starting from current ENC28760 write pointer location Parameters ptr const buffer containing bytes to be written into ENC28 760 RAM number of bytes to be written Ethernet module has to be initialized See Spi Ethernet Init Example const char buffer mikrokElektronika Spi Ethernet putConstBytes buffer 16 put const array into ENC28J60 buffer Spi_Ethernet_putString Prototype unsigned int Spi Ethernet putString unsigned char
242. ers in comments discussed later in this topic to avoid other portability problems C comments C comment is any sequence of characters placed after the symbol pair The com ment terminates at the first occurance of the pair following the initial The entire sequence including four comment delimiter symbols is replaced by one space after macro expansion In the mikroC for 8051 int type i 7 identirier parses as int 1 Note that the mikroC for 8051 does not support a nonportable token pasting strate gy using For more information on token pasting refer to the Preprocessor Operators 124 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference C comments The mikroC for 8051 allows single line comments using two adjacent slashes The comment can start in any position and extends until the next new line The following code int i this is a comment int 3 parses as int i int Nested comments ANSI C doesn t allow nested comments The attempt to nest a comment like this int declaration J fails because the scope of the first ends at the first This gives us 1g J which would generate a syntax error MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 125 CHAPTER 5 Language Reference mikroC for 8051 TOKENS Token is the smallest element of a C program that
243. ers 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 the Preferences dialog 12 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 2 1 Click the window you want to dock to give it focus Project Manager 15 52 c FirstProject mcproj ica SOURCES FirstPrajecE c 71 Header Files c Binaries gt Project level defines j Image Files 71 Output Files 71 Other Files MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 3 CHAPTER 2 Environment mikroC for 8051 Step 2 2 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 Step 3 2 3 Move the pointer over the corresponding portion of the guide diamond An out line of the window appears in the designated area 38 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Step 4 To dock the window the position indicated release the mouse button Tip To move a dockable window without snapping it into place press CTRL while dragging it Saving Layout Once you have a window layout that you lik
244. es 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 SMHz in order to use the rou tines with Dallas digital thermometers External dependencies of OneWire Library This variable must be defined in any project that is using OneWire Description Example Library extern sbit OW Bit sbit OW Bit at P2 B7 OneWire line MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 271 CHAPTER 6 Libraries mikroC for 8051 Library Routines Ow Reset Ow_Read Ow_Write Ow_Reset Prototype unsigned short Ow Reset Returns 0 if the device is present 1 1f the device 15 not present Description Issues OneWire reset signal for DS18x20 Parameters None Requires Devices compliant with the Dallas OneWire protocol Global variable ow Bit must be defined before using this function Example Issue Reset signal on One Wire Bus Ow Reset Ow_Read Data read from an external device over the OneWire bus Reads one byte of data via the OneWire bus Requires Devices compliant with the Dallas OneWire protocol Global variable ow Bit must be defined before using this function Example Read a byte from the One Wire Bus unsigned short read data read
245. es 144 Local Ree eee 144 x MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 Table of Contents TYPES sarder p bkt ARESE RRE a be Ch de ees bead ew as 145 Type Categories 146 Fundamental Types C 146 TYPES seresa Ra Oh eee oca Bpod 20 29 8508 8 RUE 147 Integral 147 Floating point Types 148 Enumerations 149 Enumeration Declaration 149 Anonymous Enum Type 150 Enumeration Scope 150 MORI TYDE zu a aoudri d deter u5 07x eo IP eee de Oe eee 151 Vold FUNCIONS sewn bo Senos 151 Generic Pointers 151 Derived TYPES a aa oe ee 151 uc rrr 152 Array Declaration 152 Array Initialization nd doa ba 152 Arrays Expressions 153 Multi dimensional Arrays 153 POROS 545 5 deh ee oa ee Be eee
246. es of Port Expander Library 284 Library Routines 284 Expander Nil ecu wem rieres GS om 285 Expander Read Byte 206 Expander Write Byte 286 Expander Read PortA 207 Expander Ikea 207 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Table of Contents mikroC for 8051 Expander Read PortAB 288 Expander 289 Expander _Write_PortB 289 Expander Vvnte 290 Expander Set 291 Expander Set DirectionPortB 291 Expander Set DirectionPortAB 292 Expander Set 292 Expander Set 293 Expander Set PullUpsPortAB 293 Library 294 HW Connection 295 EIDA saree oat a E a R E 296 External dependencies of PS 2 Library
247. escape sequences n matches a newline t a tab etc More generally xnn where nn 15 a string of hexadecimal digits matches the character whose ASCII value is nn If you need wide Unicode character code you can use x nnnn where nnnn one or more hexadecimal digits xnn char with hex code nn x nnnn char with hex code nnnn one byte for plain text and two bytes for Unicode Vt tab HT TAB same as x09 Wn newline NL same as x0a car return CR same as x0d form feed FF same as x0c a alarm bell BEL same as x07 ve escape ESC same as x1b MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 69 CHAPTER 2 Environment mikroC for 8051 Examples unsigned x20int matches unsigned int note space in the middle tunsigned matches unsigned predecessed by tab Character classes You can specify a character class by enclosing a list of characters in which will match any of the characters from the list If the first character after the is the class matches any character not in the list Examples count aeiou r finds strings countar counter etc but not countbr countcr etc count aeiou r finds strings countbr countcr etc but not countar counter etc Within a list the character is used to specify a range so that a z represents all characters between a and z inclusive If you want itself to be
248. essioni has to be lvalue and expression can be any expression The assignment expression itself is not lvalue If 1 and expression of different types the result of the expres sion2 will be converted to the type of expressioni if necessary Refer to Type Conversions for more information Compound Assignment Operators C allows more comlex assignments by means of compound assignment operators The syntax of compound assignment operators 1s MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 197 CHAPTER 5 Language Reference mikroC for 8051 expressionl op expression2 where can be one of binary operators 90 amp lt lt or gt gt Thus we have 10 different compound assignment operators amp I lt lt and gt gt All of them associate from right to left Spaces sepa rating compound operators e g will generate error Compound assignment has the same effect as expressionl expressionl op expression2 except the lvalue expressioni is evaluated only once For example expression2 is the same aS expressionl expressionl expression2 Assignment Rules For both simple and compound assignment the operands expressioni and expres sion2 must obey one of the following rules expression 15 of qualified or unqualified arithmetic type and expression2 is of arithmetic typ
249. et for detailed explaination Parameters x pos position on x axis Valid values 0 127 The parameter x pos specifies the GLCD side values from 0 to 63 specify the left side values from 64 to 127 specify the right side Note For side x axis and page layout explanation see schematic at the bottom of this page GLCD needs to be initialized see Gled Init routine Example The following two lines are equivalent and both of them select the left side of GLCD Glen Select SIde10 Glod Select Sige lo Glcd Set X Prototype void Glcd Set X unsigned short x pos Nothing Description Sets x axis position to pos dots from the left border of GLCD within the selected side Parameters 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 Gled Init routine 246 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Glcd Set Page Prototype void Glcd Set Page unsigned short Returns Description Selects page of the GLCD Parameters 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 Init routine Gled Set Page a Glcd Read Data Prototype One byte from GLCD memory Description Reads
250. eters image image to be displayed Bitmap array must be located in code memory Use the mikroC for 8051 integrated GLCD Bitmap Editor to con vert image to a constant array suitable for displaying on GLCD GLCD needs to be initialized see Init routine Example Draw image my image on GLCD Glod Image my image MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 255 CHAPTER 6 Libraries Library Example mikroC for 8051 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 declarations Glod module connections sfr char GLCD DataPort at P0 sbit sbit sbit sbit sbit sbit GLCD CS1 at P2 B0 GLCD CS2 at 2 1 GLCD RS at P2 B2 GLCD RW at P2 B3 GLCD RST at P2 B5 GLCD EN at P2 B4 End Glcd module connections void 1 25 delay ms 2000 void main unsigned short ii char someText cled Gled FILL UXxUDII 1 1 Glcd Image advanced8051 bmp 17 Giga Falli 0200 Glcd Box 62 40 124 56 1 Glod RBectanglei5 5 54 25 1 5 Giga Gap 147 GLCD data port GLCD chip select 1 signal GLCD chip select 2 signal GLCD register select signal GLCD read write signal GLCD reset signal GLCD enable signal 2 sec
251. ettings window You can change chip oscillator frequency and memory model Any change in the Project Setting Window affects currently active project only so in case more than one ect is open you have to ensure that exactly the desired project is set as active one in the Project Manager Managing Project Group mikroC for 8051 IDE provides covenient option which enables several projects 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 4 from the Project Manager window The project group may be reopend by clicking the Open Project Group Icon All relevant data about the project group is stored in the project group file extension mpg 90 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment ADD REMOVE FILES FROM PROJECT The project can contain the following file types c source files h header files binary files p1d project level defines files future upgrade image files hex asm and ist files see output files These files can not be added or removed from project other files Project Manager um 8 RS T6963C_240 126 mcproj ica S urces 6963 240x128 c EI bitmap c Header Files 6963 ica Binaries bitmapz mel Project level defines
252. eturn cursor to home position returns a shifted dis LCD RETURN HOME play to its original position Display data RAM 15 unaffected LCD CURSOR OFF Turn off cursor LCD UNDERLINE ON Underline cursor on LCD BLINK CURSOR ON Blink cursor on Move cursor left without changing display data LCD MOVE CURSOR LEFT RAM Move cursor right without changing display data LCD MOVE CURSOR RIGHT Meee Shift display left without changing display data 7 RA ve display right without changing display data Library Example The following code demonstrates usage of the LCD Library routines LCD module connections sbit LCD RS at 2 0 sbit LCD EN at 2 1 268 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries sbit LCD D7 at P2 B5 sbit LCD D6 at P2 B4 shit LCD 05 at F2 53 sbit LCD D4 at P2 B2 End LCD module connections char txtl mikroElektronika char txt2 EasyS8051B char txt3 lod44bpit char txt4 example char i Loop variable void Move Delay Function used for text moving Delay ms 500 You can change the moving speed here void main Led Init 2 Kr Initialize LCD Lcd Cmd LCD CLEAR Clear display Lcd Cmd LCD CURSOR OFF Jf Cupnspr orr 77 Write text first row LCD Out 2 6 cata Write text in second row Delay 2000
253. f parameter x that is the value whose sine is x The input parameter x must be between 1 and 1 11 The return value is in radians between 0 2 0 2 inclusive atan Prototype double atan double f Description Function computes the arc tangent of parameter f that is the value whose tangent is The return value is in radians between 0 2 and 6 2 inclusive atan2 Prototype double atan2 double y double x Description This is the two argument arc tangent function It is similar to computing the arc tangent of 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 6 inclusive ceil Prototype double ceil double x Description Function returns value of parameter rounded up to the next whole number 440 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries COS m Description Function returns the cosine of f in radians The return value is from 1 to 1 cosh Prototype double cosh double x Description returns the hyperbolic cosine of defined mathemati cally as e e X 2 If the value of is too large if overflow occurs the fails eval_poly Prototype 2 double eval poly double x const double code int n Description Calculates polynom for number with coefficie
254. f the font width Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example 1995 Sprite 5 4 elnsteln 85 118 Araw sprite 394 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi T6963C Set Cursor Prototype void Spi T6963C Set Cursor unsigned char x unsigned char y Description Sets cursor to row and column Parameters x Cursor position row number y cursor position column number Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Spi T6963C ClearBit Prototype void Spi T6963C ClearBit char b Description Clears control port bit s Parameters b bit mask The function will clear bit control port if bit in bit mask is set to 1 Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example yy clear bits 0 and I on control port opi T59630 Clearpit 0x03 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 395 CHAPTER 6 Libraries mikroC for 8051 Spi T6963C SetBit Description Sets control port bit s Parameters b bit mask The function will set bit x on control port if bit x in bit mask 15 set to 1 Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example set bits 0 and 1 on control port Spi T6963C SetBit 0x03 Spi T6
255. ftware Simulator lets you debug executable logic step by step by watching the program flow The New Project Wizard is a fast reliable and easy way to create a project Help files are syntax and context sensitive Like in any modern Windows application you may customize the layout of mikroC for 8051 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 12 MAIN MENU OPTIONS Available Main Menu options are File Edit View Project Run Tools Help Related topics Keyboard shortcuts MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 13 CHAPTER 2 Environment mikroC for 8051 FILE MENU OPTIONS The File menu is the main entry point for manipulation with the source files Mew Unik Open Save Close Ctrl F4 Print Ctrl F Exit Mew Unit Open a new editor window Open source file for editing or image file for Open Recent Files Reopen recently used file save Ctrl 5 Save changes for active editor Save the active source file with the different name or change the file type Wi Close Close active source file Ezt Exit IDE Related topi
256. h Three memory type specifiers can be used to refer to the internal data memory data idata and bdata ee M direct and indirect Accessed by Accessed by addressing direct addressing indirect addressing Bank 0 Bank 1 Bank 2 Bank 3 1F hex 16 bit addressable registers 2F hex 80 free registers TF hex 114 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 4 mikroC for 8051 8051 Specifics External Data Memory Access to external memory is slower than access to internal data memory There may be up to 64K Bytes of external data memory Several 8051 devices provide on chip XRAM space that is accessed with the same instructions as the traditional external data space This XRAM space is typically enabled via proper setting of SFR register and overlaps the external memory space Setting of that register must be manualy done in code before any access to external memory or XRAM space is made The mikroC for 8051 has two memory type specifiers that refers to external memo ry space xdata and pdata SFR Memory The 8051 provides 128 bytes of memory for Special Function Registers SFRs SFRs are bit byte or word sized registers that are used to control timers counters serial I O port I O and peripherals Refer to Special Function Registers for more information See sbit also Related topics Accessing individual bits SFRs Memory type specifiers Memory models
257. he 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 Name field modify the name of the file you want to save 5 Click the Save button MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 93 CHAPTER 2 Environment mikroC for 8051 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 CLEAN PROJECT FOLDER This menu gives you option to choose which files from your current project you want to delete Clean Project Folder Below 15 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 Se
258. how received data on PORTO Increment first received byte dat 0 Delay me 10 Red omaster 1 160 And send it back to Slave if count gt 10000 4 If loop is passed 100000 times with no message received 1 Signal receive message failure on 1 count 0 Reset loop pass counter Rs485master Send dar 1 160 P1 gt 10 4 ee 3 Re eomes ler Send oOa3L l 20 4 Retry send message If sending failed 10 times Clear PORTI Send message on broadcast address RS485 Slave code char 9 Buffer for receving sending messages char i j RS485 module connections bit rs423 Lranscelve at 3 Transmit Receive control set to P3 2 End RS485 module connections al al ee interrupt routine MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 307 CHAPTER 6 Libraries mikroC for 8051 void UartRxHandler org 0x23 0 Clear global interrupt enable flag if RI Test UART receive interrupt flag Rs485slave Receive dat UART receive interrupt detected eA receive data using RS485 communication RI 0 77 Clear UART interrier flag ER e f Set global interrupt enable flag void main PO 0 Clear ports Pl 0 Uart Init 9600 Initialize UART module at 9600 bps Delay ms 100 Rs485slave Init 160 Intialize MCU as slave address 160
259. httpCounter 0 ff counter of HTTP requests OK KKK kk kk kk kk kk kk kk kk KK Ck CK KK kk kk Funclions ET put the constant string pointed to by s to the ENC transmit buffer wf unsigned int const code char unsigned int ctr 0 while s Ethernet putByLei sTT 3 tee 348 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 CHAPTER 6 Libraries return ctr 3j je it will be much faster to use library spi Ethernet putconstString routine instead of putConstString routine above However the code will be a little bit bigger User should choose between size and speed and pick the implementation that suites him best If you choose to go with the putConstString definition above the define Jine below should be commented out derine Spi Ethernet put the string pointed to by s to the ENC transmit buffer unsigned int PUCE Cringe char 75 unsigned int ctr 0 while s mBrhernet PUCEyCS SFF 7 DESTIIT 2 return ctr I Ja IC Wiii be much faster LO use 119 Ethernel pucetring routine instead of putString routine above However the code will be a little bit bigger User should choose between size and speed and pick the implementation that suites him best If you cho
260. i Gled Set Font Spi Gled Write Char Spi Gled Write Text Spi Image Spi Glcd Init Prototype void Spi Glcd Init char DeviceAddress Description Initializes the GLCD module via SPI interface Parameters DeviceAddress Spi expander hardware address see schematic at the bottom of this page Requires SPExpanderCs and sPExpandernsT variables must be defined before using this function The SPI module needs to be initialized See Spi Init and Spi Init Advanced routines Example port expander pinout definition sbit SPExpanderRST at P1 B0 sbit SPExpanderCS at 1 1 Spi Init Advanced MASTER OSC DIV4 IDLE LOW IDLE 2 ACTIVE DATA ORDER MSB Gled Iniri 5 356 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi Glcd Set Side Prototype void SPI Glcd Set Side char x pos Description Selects GLCD side Refer to the GLCD datasheet for detail expla nation Parameters x pos position on x axis Valid values 0 127 The parameter x a specifies the GLCD side values from 0 to 63 specify the side side values from 64 to 127 specify the right Note For side x axis and page layout explanation see schematic at the bottom of this page Requires GLCD needs to be initialized for SPI communication see Spi Init routines Example following two lines are equivalent and both of them sel
261. i Init Spi Init Advanced Spi Read Spi Write Spi Init Description This routine configures and enables SPI module with the follow ing settings master mode clock idle low 8 bit data transfer most significant bit sent first serial output data changes on idle to active transition of clock state serial clock fosc 128 fosc 64 in x2 mode Requires MCU must have SPI module Example Initialize the SPI module with default settings Ilnito Jj MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 329 CHAPTER 6 Libraries mikroC for 8051 Spi Init Advanced Prototype void Spi Init Advanced unsigned short adv setting Description This routine configures and enables the SPI module with the user defined settings Parameters adv setting SPI module configuration flags Predefined library constants see the table below can be ORed to form appropriate configuration value Bit Mask Description Predefined library const Master slave and clock rate select 1 0 bits a Fosc 4 2 2 mode sient Master mode 0 11 Fosc 16 f 8 xZ mode Rm 0 Master mode Fosc 64 f 32 in x2 mode Master mode Sck Fosc 128 2 64 in x2 mode Master mode SPI clock phase 5 0x00 Data changes on idle to active IDLE 2 ACTIVE transition of the clock 0x04 Data changes on active to idle ACTIVE 2 IDL
262. ication see Spi Init routines Example Draw a box between dots 5 15 and 20 40 epi Glod l5 410 109 Spi Glcd Circle Prototype Spi Glod Lircle int x center int y center int radius echar color Description Draws a circle on GLCD Parameters x center X coordinate of the circle center Valid values 0 127 y center y coordinate of the circle center Valid values 0 63 radius radius size color color parameter Valid values 0 2 The parameter color determines the color of the circle line 0 white 1 black and 2 inverts each dot Requires GLCD needs to be initialized for SPI communication see Spi Glcd Init routines Example Draw a circle with center in 50 50 and radius 10 Gled 0 50 19 1 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 363 CHAPTER 6 Libraries 364 mikroC for 8051 Spi Glcd Set Font Prototype void SPI Glcd Set Font const char activeFont char aBFontWidth char aFontHeight unsigned int aFontOffs Description Requires Example Sets font that will be used with Spi Write Char and Spi Gled 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 bet
263. id UartRxHandler org 0x23 EA 0 Clear global interrupt enable flag ZF RI Test UART receive interrupt flag Rs48omagter Receive UART receive interrupt detected receive data using RS485 communication RI 0 Clear UART interrupt flag 1 Set global interrupt enable flag void main PO 0 Clear ports Pl O Uart Init 9600 44 Initialize UART module at 9600 bps Delay mei 100 Rs485master Init Intialize MCU as RS485 master dati Ux55 Fill buffer dat 1 0x00 dat 2 0x00 dat 4 0 Ensure that message received flag is 0 5 Us Ensure that error flag is 0 6 0 Rs485master Send dat 1 160 Send message to slave with address 160 oF message data is stored in dat Pd d message is 1 byte long ES 1 Enable UART interrupt Rl 03 Clear UART RX interrupt flag EA 1 Enable interrupts while 1 Endless loop Upon completed valid message receiving yj 4 is set to 255 306 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 CHAPTER 6 Libraries Counti Increment loop pass counter if dati 1 If error detected signal it by Pl OxAA Ff setting PORT1 to OxAA if dat 4 4 count 0 If message received successfully Reset loop pass counter Clear message received flag Read number of message received bytes for 3 lr 4 35 i S
264. ide war ew des TRAN EEG EREMO 187 Operators Precedence and Associativity 187 Arithmetic Operators 189 Arithmetic Operators Overview 189 Binary Arithmetic 189 Unary Arithmetic Operators 190 Relational Operators 191 Relational Operators Overview 191 Bitwise Operators 192 Bitwise Operators Overview 192 Logical Operations on Bit 192 Bitwise Shift Operators 193 Bitwise vs 194 Logical Operators 194 Logical Operators Overview 194 Logical lt 195 Logical Expressions and Side Effects 195 Logical VS BIUWWISG ap e ws 196 Conditional 196 Conditional Operator Rules 196 Assignment Operators 197 Simple Assignment
265. ies ANSI C Ctype Library ANSI C Math Library ANSI C Stdlib Library ANSI C String Library Miscellaneous Libraries Button Library Conversions Library Sprint Library Time Library Trigonometry Library See also Built in Routines 220 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries LIBRARY DEPENDENCIES Certain libraries use depend on function and or variables constants defined in other libraries Image below shows clear representation about these dependencies For example SPI Gled uses Gled Fonts and Port Expander library which uses SPI library This means that if you check SPI Glcd library in Library manager all libraries on which it depends will be checked too MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 22 CHAPTER 6 Libraries mikroC for 8051 LGANSE Lep _ _ LCD_Constants RS 485 UaRT SPI Ethernet HERO expander 8 Sica Fonts Port Expander SPI Lcd 4 Led Constants Port Expander 8 SPI LCD8 LCE Led Constants Port Expander _ SPI_T69636 Tig Sprint ctype Sinn Related topics Library manager 000 8051 Libraries Ctype _ 6963 Trigon 2 222 MIKROELEKTRONIKA SOFTWARE AND HARDWARE
266. if case sensitivity 15 turned off Keywords remain case sensitive and they must be written in lower case Uniqueness and Scope Although identifier names are arbitrary according to the stated rules if the same name is used for more than one identifier within the same scope and sharing the same name space then error arises Duplicate names are legal for different name spaces regardless of scope rules For more information on scope refer to Scope and Visibility Identifier Examples Here are some valid identifiers temperature Vi Pressure no hit dat2string SUMS VEERG and here are some invalid identifiers 7temp NO cannot begin with a numeral Shigher NO cannot contain special characters int NO cannot match reserved word j23 07 04 NO cannot contain special characters dot 136 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference PUNCTUATORS The mikroC for 8051 punctuators also known as separators are Brackets Parentheses 11 Braces Comma Semicolon Colon Asterisk Equal sign Pound sign Most of these punctuators also function as operators Brackets Brackets 1 indicate single and multidimensional array subscripts char ch str mikro int mat 3 4 3 x 4 matrix gh mbH 33 4th element Parentheses Parentheses are us
267. ified width all characters are output The precision field 1s a non negative number that specifies a number of characters to print number of significant digits or number of decimal places The precision field can cause trunca tion or rounding of the output value in the case of a floating point number as specified in the following table MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 463 CHAPTER 6 Libraries mikroC for 8051 Description Meaning of the precision field The precision field is where you specify a mini mum number of digits that will be included in the output value Digits are not truncated if the number of digits in the argument exceeds that defined in the precision field If a number of dig its in the argument is less than the precision field the output value is padded on the left with The precision field is where you specify a num ber of digits to the right of the decimal point The last digit is rounded The precision field is where you specify a num ber of digits to the right of the decimal point The last digit 15 rounded The precision field is where you specify a maxi mum number of significant digits in the output The precision field has no effect on these field The precision field is where you specify a maxi mum number of characters in the output value Excess characters are not output The optional characters 1 L may immediately precede conver sion type to respecti
268. in a source file must be matched by a closing endif directive Any number of 1 directives can appear between 1 and endif directives but at most one eise directive is allowed The 15 directive if present must be the last directive before endif sections can be any program text that has meaning to compiler or preprocessor The preprocessor selects a single section by evaluating constant expression fol lowing each if or 1 directive until it finds a true nonzero constant expres sion The constant expressions are subject to macro expansion MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 217 CHAPTER 5 Language Reference mikroC for 8051 If all occurrences of constant expression are false or if no 1 directives appear the preprocessor selects the text block after the 15 clause If the 1 clause 15 omitted and all instances of constant expression in the if block are false no section Is selected for further processing Any processed section can contain further conditional clauses nested to any depth Each nested else elif or endif directive belongs to the closest preceding the if directive The net result of the preceding scenario is that only one code section possibly empty will be compiled Directives ifdef and ifndef The ifdef and ifndef directives can be used anywhere 1 can be used and they can test whether an identifier is currently defined or no
269. ing Onewire reset signal Issue command SKIP ROM Issue command CONVERT T Issue command SKIP ROM Issue command READ SCRATCHPAD temp Ow Read temp Ow Read lt lt 9 Lemp Format and display result on Lcd Display Temnperacure temp Delay me 500 while 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 25 CHAPTER 6 Libraries mikroC for 8051 HW Connection 1259C 509C VCC VCC l vcc O DQ vcc gt ut l Reset i o f i N oc P25 i P2 4 OSCILLATOR P2 3 dos XTAL1 P2 1 GND P2 0 VCC 10K zelela a L lek LCD 2X16 6 5 Example of DS1820 connection 276 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries MANCHESTER CODE LIBRARY The mikroC for 8051 provides a library for handling Manchester coded signals The Manchester code is a code in which data and clock signals are combined to form a single self synchronizing data stream each encoded bit contains a transition at the midpoint of a bit period the direction of transition determines whether the bit is 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 Bi phase codi
270. ing UART HW module needs to be initialized See Uart_ Init Example 44 rs485 module pinout Spit 15465 transceive at P3 B2 transmit receive control set to port3 bit2 Uart Init 9600 74 initialize usart module Rs485slave Init 160 intaialise a Slave for RS 485 communication with address 160 RS485slave Receive Prototype void RS4B5slaye Receive char data buffer Returns Nothing Description Receives messages from Master If Slave address and Message address field don t match then the message will be discarded Messages are multi byte so this routine must be called for each byte received Parameters data buffer 6 byte buffer for storing received data in the fol lowing manner data 0 2 message content data 3 number of message bytes received 1 3 4 is set to 255 when message is received data 5 15 set to 255 if error has occurred The function automatically adjusts 41 and 5 upon every received message These flags need b be een by soft ware Requires MCU must be initialized as a Slave for RS 485 communication See RS485slave Init Example char msg RS485slave Read msg 304 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries RS485slave_Send Prototype void Rs485slave Send char data buffer char datalen Description Sends message to Master Message format can be
271. initialized See Spi Ethernet Init Example char buffer buffer Spi Ethernet getByte read a byte from ENC28J60 buffer MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 343 CHAPTER 6 Libraries mikroC for 8051 Spi Ethernet getBytes Prototype void Spi Ethernet getBytes unsigned char ptr unsigned int addr unsigned char n Description This is MAC module routine It fetches equested number of bytes from NC28760 RAM starting from given address If value of OxFFFF 15 passed as the address parameter the reading will start from current ENC28J60 read pointer ERDPT location Parameters ptr buffer for storing bytes read from ENc28760 RAM addr ENC28760 RAM start address Valid values 0 8192 n number of bytes to be read Requires Ethernet module has to be initialized See Spi Ethernet Init Example char buffer 16 Spi Ethernet getBytes buffer 0x100 16 read 16 bytes starting from address 0x100 344 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi_Ethernet_UserTCP Prototype unsigned int Spi Ethernet UserTCP unsigned char remoteHost unsigned int remotePort unsigned int localPort unsigned int reqLength Returns 0 there should not be a reply to the request Length of TCP HTTP reply data field otherwise Description This is TCP module routine It is internally called by the library
272. ion Function returns the value of raised to the power i e xY If x is negative the function will automatically cast y into unsigned Long 442 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries sin Function returns the sine of f in radians The return value is from 1 to l sinh Prototype double sinh double x Description Function returns the hyperbolic sine of x defined mathematically as c e 2 If the value of x is too large if overflow occurs the function fails sqrt Prototype double sqrt double x Function returns the non negative square root of x tan Prototype Description Function returns the tangent of x in radians The return value spans the allowed range of floating point in the mikroC for 8051 tanh Description Function returns the hyperbolic tangent of x defined mathemati cally as sinh cosh MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 443 CHAPTER 6 Libraries mikroC for 8051 ANSI C STDLIB LIBRARY The mikroC for 8051 provides a set of standard ANSI C library functions of gener al utility Note Not all of the standard functions have been included Note Functions have been mostly implemented according to the ANSI C standard but certain functions have been modified in order to facilitate 8051 programming Be sure to skim through the description before using sta
273. ires Example 0 upon successful packet processing zero packets received or received packet processed successfully 1 upon reception error or receive buffer corruption ENC28J60 controller needs to be restarted 2 received packet was not sent to us not our IP nor IP broad cast 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 amp ICMP requests are replied automatically upon TCP request the Spi Ethernet UserTCP function is called for further processing upon UDP request the Spi Ethernet UserUDP function is called for further processing Note Spi Ethernet doPacket must be called as often as possi ble in user s code Ethernet module has to be initialized See Spi Ethernet Init while 1 1 Spi Ethernet doPacket process received 340 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi_Ethernet_putByte Prototype void Spi Ethernet putByte unsigned char v Description This is MAC module routine It stores one byte to address point ed by the current 282760 write pointer EWRPT Parameters v value to store Requires Ethernet module has to be initialized See Spi Ethernet Init Example char data Spi Eth
274. it by default use of the storage class specifier static or extern Each instance of a particular identifier with external linkage represents the same object or function throughout the entire set of files and libraries making up the pro gram Each instance of a particular identifier with internal linkage represents the same object or function within one file only Linkage Rules Local names have internal linkage the same identifier can be used in different files to signify different objects Global names have external linkage identifier signifies the same object throughout all program files If the same identifier appears with both internal and external linkage within the same file the identifier will have internal linkage Internal Linkage Rules 1 names having file scope explicitly declared as static have internal linkage 2 names having file scope explicitly declared as const and not explicitly declared as extern have internal linkage typedef names have internal linkage 4 enumeration constants have internal linkage UJ MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 175 CHAPTER 5 Language Reference mikroC for 8051 External Linkage Rules 1 names having file scope that do not comply to any of previously stated internal linkage rules have external linkage The storage class specifiers auto and register cannot appear in an external decla ration No more than one external definition
275. ized See the T6963C Init routine T6963C Cursor Height 7 424 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries T6963C Graphics Prototype Description Enable disable graphic displaying Parameters on off parameter Valid values 0 disable graphic dispaying and 1 enable graphic displaying Requires Toshiba GLCD module needs to be initialized See the 6963 Init routine Example enable graphic displaying 189522 Grapalesql T6963C Text Prototype void 6963 Text char n Description Enable disable text displaying Parameters on off parameter Valid values 0 disable text dispaying and 1 enable text displaying Requires Toshiba GLCD module needs to be initialized See the T6963C_ Init routine Example enable text displaying T6963C Text 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 425 CHAPTER 6 Libraries mikroC for 8051 T6963C Cursor Prototype void T6963C Cursor char Description Set cursor on off Parameters n on off parameter Valid values 0 set cursor off and 1 set cursor on Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Example set cursor on Cursorti T6963C Cursor Blink Prototype void T6963C Cursor Blink char n Description Enable disable cursor blinking Parameters n on off parame
276. ke MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 65 CHAPTER 2 Environment mikroC for 8051 LCD Custom Character mikroC for 8051 includes the LCD Custom Character Output is mikroC for 8051 compatible code You can launch it from the drop down menu Tools LCD Custom Character E LCD custom character ax EG i 5 E m m hx 5x10 Load Fill all Clear all Invert Preview f Be 10 cursar line AGE address Char Char data row GENERATE 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 professi onals Tools The mikroC for 8051 includes the Tools tab which enables the use of shortcuts to external programs like Calculator or Notepad You can set up to 10 different shortcuts by editing 10 Tool9 66 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 Options J Editor Tooli Tool Tool3 Tool J Output CHAPTER 2 Environment Macro FILE NAME MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 67 CHAPTER 2 Environment mikroC for 8051 Output settings By modifying Output Settings user can configure the content of the output files You can enable or disable for example generation of ASM and List fi
277. kroC for 8051 ANSI C STRING LIBRARY The mikroC for 8051 provides a set of standard ANSI C library functions useful for manipulating strings and RAM memory Note Not all of the standard functions have been included Note Functions have been mostly implemented according to the ANSI C standard but certain functions have been modified in order to facilitate 8051 programming Be sure to skim through the description before using standard C functions Library Functions memchr memcmp memcpy memmove memset Strcat strchr strcmp Strcpy strlen strncat Strncpy Strspn strncmp strstr Strcspn strpbrk strrchr memchr Prototype void memchr void char n unsigned int v Description Function locates the first occurrence of n in the initial v bytes of memory area starting at the address The function returns the pointer to this location or 0 if the n was not found For parameter p you can use either a numerical value literal vari able constant memory address dereferenced value of an object for example amp mystring or amp PO 448 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries memcmp Prototype int memcmp void 51 void s2 int n Description Function compares the first n characters of objects pointed to by si and s2 and returns zero if the objects are equal or returns a diffe
278. kroC for 8051 HW Connection OSCILLATOR o LL Lo SS OSIIN 6 12 SPI Ethernet 354 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries SPI GRAPHIC LCD LIBRARY The mikroC for 8051 provides a library for operating Graphic LCD 128x64 with commonly used Samsung KS108 KS107 controller via SPI interface For creating a custom set of GLCD images use GLCD Bitmap Editor Tool 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 External dependencies are the same as Port Expander Library external dependen cies Library Routines Basic routines Spi Gled Init Spi Gled Set Side Spi Set Page Spi Gled Set X Spi Gled Read Data Spi Gled Write Data Advanced routines Spi Gled Fill Spi Dot Gled Line Spi Gled V Line Spi Gled Line MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 355 CHAPTER 6 Libraries mikroC for 8051 Spi Rectangle Spi Box Spi Circle Sp
279. ks here MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 457 CHAPTER 6 Libraries mikroC for 8051 LongWordToStr Prototype void LongWordToStr unsigned long input char output Nothing Converts input unsigned long integer number to a string The out put string has fixed width of 11 characters including null character at the end string termination The output string is right justified m 1 remaining positions the left if any are filled with anks Description Parameters input unsigned long integer number to be converted output destination string Destination string should be at least 11 characters in length unsigned long jj 3700000 char txt 11 Example LongToctr 11 y txt ig 3700000 three blanks here FloatToStr uin mE char FloatToStr float fnum unsigned char Prototype E 3 if input number is NaN 2 if input number 15 INF if input number is INF 0 if conversion was successful Converts a floating point number to a string Parameters num floating point number to be converted Description 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 Destination string should be at least 14 characters in length float ffl float ff2 123 4567 9 float ff3 0 00000123
280. lculating scalar product of two vectors using the while statement int s 0 i 0 while 1 lt ala itti Note that body of the loop can be a null statement For example while qt MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 205 CHAPTER 5 Language Reference mikroC for 8051 DO STATEMENT The do statement executes until the condition becomes false The syntax of the do statement is do statement while expression The statement 15 executed repeatedly as long as the value of expression remains non zero The expression 15 evaluated after each iteration so the loop will execute statement at least once Parentheses around expression are mandatory Note that do is the only control structure in C which explicitly ends with semi colon Other control structures end with statement which means that they implicitly include a semicolon or closing brace Here is an example of calculating scalar product of two vectors using the do state ment do Ss Bis while i FOR STATEMENT The for statement implements an iterative loop The syntax of the for statement is for init expression condition expression increment expres sion statement Before the first iteration of the loop init expression sets the starting variables for the loop You cannot pass declarations in init expression condition expression 1s ch
281. le Options J Editor Output Settings V Generate ASM Include HEX opcodes Output Settings v Include ROM constants Y Include ROM Addresses V Generate list file VY Include debug info Y Include source lines in output files Optimization level Four i Compiler Case sensitive 68 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment 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 mean ing described below A series of characters matches that series of characters in the target string so the pattern short would match short in the target string You can cause characters that normally function as metacharacters or escape sequences to be interpreted by preceding them with a backslash For instance metacharacter matches beginning of string but matches character and matches etc Examples unsigned Matches string unsigned unsigned Matches string unsigned Escape sequences Characters may be specified using a
282. le reads values of the pressed keys on the PS 2 keyboard and sends them via UART char keydata 0 special 0 down 0 PS2 module connections sbit PS2 DATA at sbit 52 CLOCK at 1 End PS2 module connections void main Uart Init 4800 Initialize UART module at 4800 bps Pas Sontag Initialize PS 2 Keyboard Delay 100 Wait for keyboard to finish do Endless loop if Ps2 Key Read amp keydata amp special amp down If data was read from PS 2 if down amp amp keydata 16 Backspace read Uart Write 0x08 Send Backspace to usart terminal else if down 55 keydata 13 4 Enter read Uart Write r Send carriage return to usart terminal yy Usrt Nrite in s Uncomment this line if usart terminal also expects line feed for new line transition else if down 55 special 66 keydata Common key read Uart Write keydata Send key to usart terminal Delay 5 10 44 Debounce period while 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 299 CHAPTER 6 Libraries mikroC for 8051 HW Connection vcc o VCC VCC 1 1 5 NC 8568 1 NC DATA OSCILLATOR Example of PS2 keyboard connection 300 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries RS 485 LIBRARY RS 485
283. lear and all libraries will be cleared from the project Only the selected libraries will be linked Library Manager E lt Button L Conversions Doprntr Doprnti Daprntl wv lcd m led Fonts Led Constants a Math ld One wire E R5485 Sofware izc v Sofware SPI Software Wart Sound Sprint Sprinti Sprint String T6963 Time Trigon s LIART l l SOSOOO000008000 E El Er Ee E E MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Refresh Library by scanning files in Uses folder Useful when new libraries are added by copying files to Uses folder able and need refreshing Include all available libraries current project No libraries from the list will be included in current project Restore library to the state just before last project saving Related topics mikroC for 8051 Libraries Creating New Library Rebuild all available libraries Useful when library sources avail MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 51 CHAPTER 2 Environment mikroC for 8051 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
284. lect text from starting delimiter to ending delimiter Go to ending delimiter Indent selected code lines Outdent selected code lines Generate HTML code suitable for publishing current source code on the web 22 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Find Replace Toolbar Find Replace Toolbar is a standard toolbar with following options ind Find text in current editor Find next occurence Find previous occurence Replace text Project Toolbar Project Toolbar comes with following options deon Dewnpon 00000 Open new project wizard wizard Open Project Add existing project to project group Remove existing project from project group MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 23 CHAPTER 2 Environment mikroC for 8051 Add File To Project Remove File From Project Close current project Build Toolbar Build Toolbar comes with following options DLL MN LLL NN Debugger Debugger Toolbar comes with following options 24 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment ____ Office 2003 Silver Office 2003 Olive Office FP Styles toolbar allows you to easily customize your workspace MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 29 CHAPTER 2 Envi
285. lect which files you want to remove fram the project folder Please note that selected files will be permanently deleted from your disk if you click LedBlinking asm LedBlinking c LedBlinking cp LedBlinking dbg LedBlinking dct LedBlinking dlt LedBlinking hex LedBlinking ihex LedBlinking ini LedBlinking lst LedBlinking LedBlinking mcproj LedBlinking mcproj_callertable txt LedBlinking mil LedBlinking user dic Clean Cancel C Program Files Mikroelektronikatmikro 8051T1Examples ed Blinking 94 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 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 from the Project Toolbar If more more than one project is open you 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 mikroC for 8051 will generate output files OUTPUT FILES Upon successful compilation the mikroC for 8051 will generate output files in the project folder folder which contains the project file mcproj Output files a
286. les generated to file path specified by filename B Save compiled binary files c1 to directory O Miscellaneous output options Generate debug info E Set memory model opts s small compact large L Check and rebuild new libraries Turn on case sensitivity Example mikroc8051 exe MSF DBG pAT89S8253 ES 011111114 fo10 N C Led Lced mcproj SP C Program Files Mikroelektronika mikroC 8051 defs SP C ProgramFiles Mikroelektronika mikroC 8051 uses SP C Led Lcd c System mcl Math mcl Math Double mcl Delays mcl Lib Lcd mcl Lib LcdConsts mcl Parameters used in the example MSF Short Message Format used for internal purposes by IDE Generate debug info 178958253 MCU 8958253 selected ES Set small memory model 011111114 Miscellaneous output options 010 Set oscillator frequency in MHz N C Led Led mcproj SP C ProgramFiles Mikroelektronika mikroC 8051 defs Output files generated to file path specified by filename SP C Program Files Mikroelektronika mikroc 8051 defs Add directory to the search path list SP C Program Files Mikroelektronika mikroc 8051 uses Add directory to the search path list oP Or bed Lode System mol Math mol Math Double mcl Delays mel Lodoncl Lib LoOConstsmol Add directory to the search path list MIKROELEKTRONIKA SOFTWARE AND
287. lex In ANSI C the primary expressions are constant also referred to as literal identi fier and expression defined recursively Expressions are evaluated according to a certain conversion grouping associativi ty and precedence rules which depends on the operators used presence of parenthe ses and data types of the operands The precedence and associativity of the opera tors are summarized in Operator Precedence and Associativity The way operands and subexpressions are grouped does not necessarily specify the actual order in which they are evaluated by the mikroC for 8051 Expressions can produce lvalue rvalue or no value Expressions might cause side effects whether they produce a value or not COMMA EXPRESSIONS One of the specifics of C is that it allows using of comma as a sequence operator to form so called comma expressions or sequences Comma expression is a comma delimited list of expressions it 1s formally treated as a single expression so it can be used in places where an expression 1s expected The following sequence Expression 1 22 results in the left to right evaluation of each expression with the value and type of expression 2 giving the result of the whole expression Result of expression 11S discarded Binary operator comma has the lowest precedence and associates from left to right so thata b cisthesameas a c This allows writing sequences with
288. lex data structures almost as easily as single vari ables Note the mikroC for 8051 does not support anonymous structures ANSI diver gence MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 161 CHAPTER 5 Language Reference mikroC for 8051 Structure Declaration and Initialization Structures are declared using the keyword struct struct tag member declarator list Here tag is the name of a structure member declarator list is a list of structure members actually a list of variable declarations Variables of structured type are declared the same as variables of any other type The member type cannot be the same as the struct type being currently declared However a member can be a pointer to the structure being declared as in the fol lowing example struct mystruct imystruct illegal Struct imvastruct j 7 Also a structure can contain previously defined structure types when declaring instance of declared structure Here is an example Structure defining a dot struct Dot float x y Structure defining a circle struct Circle float r struct Dot center Ol 023 declare variables ol and o2 of Circle Note that the structure tag can be omitted but then additional objects of this type cannot be declared elsewhere For more information see the Untagged Structures below Structure is initialized by assigning
289. lues 0 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right X coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the color of the rectangle border 0 white 1 black and 2 inverts each dot Requires GLCD needs to be initialized for SPI communication see Spi_Glcd_Init routines Example Draw a rectangle between dots 5 5 and 40 40 Glod Bectangleto 5 40 40 17 362 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi Glcd Box Prototype void Spi Glcd Box char x upper left char y upper lert char x bottom right char y bortoum right char color Description Draws a box on GLCD Parameters x upper left X coordinate of the upper left box corner Valid values 0 127 y upper left y coordinate of the upper left box corner Valid values 0 63 x bottom right X coordinate of the lower right box corner Valid values 0 127 y bottom right y coordinate of the lower right box corner Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the color of the box fill 0 white black and 2 inverts each dot Requires GLCD needs to be initialized for SPI commun
290. ly code memory type specifier is used to refer to program memory 8051 memory organization alows external program memory to be added How does the microcontroller handle external memory depends on the pin EA log ical state Address FFFF hex EA pin 1 gt EA pin 0 Address FFFF hex Address 4000 hex Address hex Microcontroller MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 113 CHAPTER 4 8051 Specifics mikroC for 8051 Internal Data Memory Up to 256 bytes of internal data memory are available depending on the 8051 deriv ative Locations available to the user occupy addressing space from 0 to 7Fh 1 first 128 registers and this part of RAM is divided several blocks The first 128 bytes of internal data memory are both directly and indirectly addressable The upper 128 bytes of data memory from 0x80 to OxFF can be addressed only indi rectly Since internal data memory is used for CALL stack also and there is only 256 bytes splited over few different memory areas fine utilizing of this memory is crucial for fast and compact code See types efficiency also Memory block in the range of 20h to 2Fh is bit addressable which means that each bit being there has its own address from 0 to 7Fh Since there are 16 such registers this block contains in total of 128 bits with separate addresses Bit 0 of byte 20h has the bit address 0 and bit 7 of byte 2Fh has the bit address 7F
291. m of this page Requires GLCD needs to be initialized see Gled Init routine Use Set Font to specify the font for display if no font is speci fied then default 5x8 font supplied with the library will be used Example Write character C on the position 10 inside the page 2 Glod Write Char 6c 254 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Glcd Write Text Prototype void Glcd Write Text char text unsigned short x pos unsigned short page num unsigned short color Description Prints text on GLCD Parameters text text to be written _ x pos text starting position on X axis page num the number of the page on which text will be written Valid values 0 7 color color parameter Valid values 0 2 The parameter color determines the color of the text 0 white 1 black and 2 inverts each dot Note For x axis and page layout explanation see schematic at the bottom of this page Requires GLCD needs to be initialized see Gled Init routine Use Glcd_ Set Font to specify the font for display if no font is speci fied then default 5x8 font supplied with the library will be used Example Write text Hello world on the position 10 inside the page 2 Glod Write vorid Glcd Image Prototype void Glcd Image code const unsigned short image Description Displays bitmap on GLCD Param
292. ment 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 Bookmarks and Goto Line 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 sy or press F12 key MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 41 CHAPTER 2 Environment mikroC for 8051 Options Editor lt Editor Settings Editor Settings project Fite tis l Restore Last Opened Project E T Restore All Opened Files V Save Breakpoints Auto Corect Save Bookmarks If Opened File Is Externally Modified Reload file but do not prompt Ignore externally made changes Auto Save Y Enable Auto Save Timeout Interval 3 minutes Highlighter Highlight begin pairs X Highlight brackets 7 Check Spelling Comment style O H single line Advanced Editor Options Open options dialog
293. model can accom modate a maximum of 256 bytes of variables The limitation 1s due to the address ing scheme used which is indirect through registers RO and This memory model is not as efficient as the small model and variable access 1s not as fast However the compact model 15 faster than the large model mikroC for 8051 uses the RO and 1 operands to acess external memory with instructions that use 8 bit wide pointers and provide only the low order byte of the address The high order address byte or page 1s provided by Port 2 on most 8051 derivates see data sheet for details 116 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 4 mikroC for 8051 8051 Specifics Large model In the large model all variables reside in external data memory which may be up to 64K Bytes This is the same as if they were explicitly declared using the xdata memory type specifier The DPTR is used to address external memory Instruction set is not optimized for this memory model access to external memory so it neeeds more code than the small or compact model to manipulate with the variables char xadd char al char a2 large allocate parameters and local variables in xdata space return al a2 Related topics Memory type specifiers 8051 Memory Organization Accessing individual bits SFRs Project Settings MEMORY TYPE SPECIFIERS The mikroC for 8051 supports usage of all memory are
294. motePort unsigned int destPort unsigned int reqLength Library Routines Spi Ethernet Init Ethernet Enable Spi Ethernet Disable Spi Ethernet doPacket Spi Ethernet putByte Spi Ethernet putBytes 817 Description request handler UDP request handler Example sfr sbit Spi Ethernet CS at sfr sbit Spi Ethernet BST at Example Refer to the library example at the bottom of this page for code implementation Refer to the library example at the bottom of this page for code implementation MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 335 CHAPTER 6 Libraries mikroC for 8051 Spi Ethernet putString Spi Ethernet putConstString Spi Ethernet putConstBytes Spi Ethernet getByte Spi Ethernet getBytes Spi Ethernet UserTCP Spi Ethernet UserUDP Spi Ethernet Init Prototype void Spi Ethernet Init unsigned char mac unsigned char ip unsigned char fullDuplex Returns Nothing Description This is MAC module routine It initializes ENC28J60 controller This function is internaly splited into 2 parts to help linker when coming short of memory ENC28J60 controller settings parameters not mentioned here are set to default receive buffer start address 0x0000 receive buffer end address 0x19AD transmit buffer start address 0 1 transmit buffer end address 0x1FFF RAM buffer
295. n 8bit mode via spi Spi Lcd8 Out Prototype void 5 Lcd8 Out unsigned short row unsigned short column char text Description Prints text on LCD starting from specified position Both string variables and literals can be passed as a text Parameters row Starting position row number column Starting position column number text text to be written Requires LCD needs to be initialized for SPI communication see Spi Led8 Config routines Example Write text Hello on LCD starting from row 1 column 33 opi Outil 2 378 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi Lcd8 Out Description Prints text on LCD at current cursor position Both string vari ables 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 Led8 Config routines Example Write text Here at current cursor position Leds tur Spi Lcd8 Chr Prototype void Spi 2 short row unsigned short column char out char Description Prints character on LCD at specified position Both variables and literals can be passed as character Parameters row writing position row number column writing position column number out char character to be written Requires LCD needs to be initialized for SPI
296. n TOSHI BA T6963C controller via SPI interface The Toshiba T6963C is a very popular LCD controller for the use in small graphics modules It is capable of controlling displays with a resolution up to 240x128 Because of its low power and small out line it is most suitable for mobile applications such as PDAs MP3 players or mobile measurement equipment Although this controller 15 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 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 GLCD 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 RS C D E External dependencies of Spi T6963C Graphic LCD Library The implementation of Spi T6963C Graphic LCD Library routines is based on Port Expander Library routines External dependencies are the same as Port Expander Library external dependencies 384 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHA
297. n case of func itis the typedef declaration There can be many referencing declarations for the same identifier especially in a multifile program but only one defining declaration for that identifier is allowed For example MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 173 CHAPTER 5 Language Reference mikroC for 8051 Here is a nondefining declaration of function max it merely informs compiler that max is a function int max Here is a definition of function max int max int x int y return x gt y x y Definition of variable i int 1 Following line is an error i is already defined int 1 Declarations and Declarators The declaration contains specifier s followed by one or more identifiers declara tors The declaration begins with optional storage class specifiers type specifiers and other modifiers The identifiers are separated by commas and the list is termi nated by a semicolon Declarations of variable identifiers have the following pattern storage class type qualifier type vari initl var2 init2 e where vari var2 any sequence of distinct identifiers with optional initial izers Each of the variables is declared to be of type if omitted type defaults to int The specifier storage class can take the values extern static regis ter or the default auto Optional type qualifier can take values con
298. n chip RAM of the 8051 It has the shortest fastest access time but the amount of data is limited in size to 128 bytes or less puts x in data ram unsigned char data x Indirectly addressable internal data memory accessed across the full internal address space 256 bytes This memory is indirectly accessed using 8 bit addresses and is the on chip RAM of the 8051 The amount of idata 15 lim ited in size to 128 bytes or less it is upper 128 addresses of RAM puts x in data ram unsigned char data x CHAPTER 4 mikroC for 8051 8051 Specifics bdata Description Bit addressable internal data memory supports mixed bit and byte access 16 bytes This memory is directly accessed using 8 bit addresses and is the on chip bit addressable RAM of the 8051 Variables declared with the bdata type are bit addressable and may be read and written using bit instructions For more information about the bdata type refer to the Accessing Individual Bits Example puts x in data ram unsigned char data x xdata Description External data memory 64 KBytes accessed by opcode MOVX DPTR This memory is indirectly accessed using 16 bit addresses and is the external data RAM of the 8051 The amount of xdata 15 limited in size to 64K or less Example puts x in data ram unsigned char data x MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 119 CHAPTER 4 8051 Specifics mikroC for 8051
299. n negative mode i e white text on black background AND Mode The text and graphic data shown on the display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example opi T6963C Writs Iext GLOD LIBRARY DEMO WELCOME 0 0 T6963C ROM MODE EXOR MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 39 CHAPTER 6 Libraries mikroC for 8051 Spi T6963C Line Prototype Spi 70620302 Line int x0 int yO int xl int yl unsigned char pcolor Description Draws a line from x0 y0 to x1 y1 Parameters x0 X coordinate of the line start y0 y coordinate of the line end x1 X coordinate of the line start y1 y coordinate of the line end pcolor color parameter Valid values Spi T6963C BLACK and Spi 6963 WHITE Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example 5 T6963C Line 0 0 239 127 T6963C WHITE Spi T6963C Rectangle Prototype Spi T55392C PRectangle int int int xl int yl unsigned char pcolor Description Draws a rectangle on GLCD Parameters x0 X coordinate of the upper left rectangle corner
300. nction Example Initialize Receiver sbit MANRXPIN at Man Receive Init 278 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Man_Receive Prototype unsigned char Man Receive unsigned char error A byte read from the incoming signal Description The function extracts one byte from incoming signal Parameters error error flag If signal format does not match the expected the error flag will be set to non zero Requires To use this function the user must prepare the MCU for receiv ing See Man Receive Init Example unsigned char data 0 error 0 dara e Man Recelve berror if error error handling Man Send Init Prototype The function configures Transmitter pin MANTXPIN variable must be defined before using this function Example 7 dinitialige Transmitter sbit MANTXPIN at P1 B1 Send IBLL 0 3 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 279 CHAPTER 6 Libraries mikroC for 8051 Man Send Prototype void Man Send unsigned char tr data Description Sends one byte Parameters tr data data to be sent Note Baud rate used is 500 bps Requires TO use this function the user must prepare The MCU Tor sending See Man Send init Example unsigned char msg Man Send msg Man Synchro Prototype unsigned int Man Synchro Returns 0 if synchronizati
301. nd end but beyond this function any surplus whitespace 15 discarded For example two sequences int i float f and int float f are lexically equivalent and parse identically to give six tokens int Whitespace in Strings The ASCII characters representing whitespace can occur within string literals In that case they are protected from the normal parsing process they remain as a part of the string For example char name mikro foo parses into seven tokens including a single string literal token char name mikro Too just one token here MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 123 CHAPTER 5 Language Reference mikroC for 8051 Line Splicing with Backslash A special case occurs if a line ends with a backslash Both backslash and new line character are discarded allowing two physical lines of a text to be treated as one unit So the following code mikro 4 Compiler parses into mikroC Compiler Refer to String Constants for more information COMMENTS Comments are pieces of a text used to annotate a program and technically are anoth er form of whitespace Comments are for the programmer s use only they are stripped from the source text before parsing There are two ways to delineate com ments the C method and the C method Both are supported by mikroC for 8051 You should also follow the guidelines on the use of whitespace and delimit
302. ndard C functions Library Functions abs atof atol atol div Idiv uldiv labs max min rand srand Xtoi abs Function returns the absolute 1 positive value of a 444 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries atof Prototype double atof char Description Function converts the input string s into a double precision value and returns the value Input string s should conform to the floating point literal format with an optional whitespace at the beginning The string will be processed one character at a time until the function reaches a character which it doesn t recognize including a null character Prototype int atoi char 5 Description Function converts the input string s into an integer value and returns the value The input string s should consist exclusively of decimal digits with an 1 whitespace and a sign at the beginning The string will be processed one character at a time until the function reaches a character which it doesn t recognize including a null character atol Prototype long atol char Description Function converts the input string s into a long integer value and returns the value The input string s should consist exclusively of decimal digits with an optional whitespace and a sign at the beginning The string m be processed one character at a time u
303. nder s PORTA and PORTB pull up resis LOIS Expander Set PullUDSPOrFrLAB U MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 293 CHAPTER 6 Libraries mikroC for 8051 Library Example The example demonstrates how to communicate with Port Expander MCP23S17 Note that Port Expander pins A2 Al AO are connected to GND so Port Expander Hardware Address is 0 unsigned char i 0 Port Expander module connections sbit SPExpanderRST at P1 B0 sbit SPExpanderCS at 1 1 End Port Expander module connections void main Init 77 Initialize SPI module Expander Initialize Port Expander Expander Set 0200 Set Expander s PORTA to be output Expander Set DirectionPOPLBi iD U0xFP j Set Expander s PORTB to be input Expander Set PullUpsPortB 0 U0XxFP Set pull ups to all of the Expander s PORTB pins while 1 Endless loop Expander Write PortA 0 144 Write i to expander s PORTA Expander Read PortBiu Read expander s PORTB and write it to PORTO Delay ms 100 7 294 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries HW Connection p e 9 85681 1 6 7 Port Expander HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WO
304. ndirec tion operator to a pointer to one past the last element leads to undefined behavior For example 160 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference void f some type af int n function f handles elements of array a array has n elementos some type y int i some type p amp a 01 for i 4 nj id 4 here we do something with p ptt and with the last iteration p exceeds the last element of array a at this point p is undefined Pointer Subtraction similar to addition you can use operators and to subtract an integral value from a pointer Also you may subtract two pointers The difference will be equal to the distance between two pointed addresses in bytes For example int a 10 int pil 0 int pi2 al 41 l1 s pi pil i equals 8 pis 1 oe IBI f ie ms Br Pir BOW to 7y STRUCTURES A structure 1s a derived type usually representing a user defined collection of named members or components These members can be of any type either fundamental or derived with some restrictions to be discussed later in any sequence In addi tion a structure member can be a bit field Unlike arrays structures are considered to be single objects The mikroC for 8051 structure type lets you handle comp
305. ne mess Q Used Pdeta RAM EXE Free Pdata Special Function Registers Summarizes all Special Function Registers and their addresses Specia incon register SFR MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 55 CHAPTER 2 Environment mikroC for 8051 General Purpose Registers Summarizes all General Purpose Registers and their addresses Also displays symbolic names of variables and their addresses Statistics S Memory Usage EL RAM General purpose registers GPR data bData Pdata i SFR ROM ROM Allocation Procedures Size Locations advanced8051_bmp _advanced6051_ bmp C51 GLCD C51 GLCD C52 LG LCD CS 2 BLCD RS LGLCD GLCD LGLCD Fw LGLCD_RST ROM Memory Usage Displays ROM memory usage in form of histogram Statistics Memory Usage RAM ROM Memory Usage locations dn Free ROM 80 of 12 257 BE iD ata bData Pdata SFR GPR ERROM ROM Allocation Procedures Size Locations Used ROM 20 of 12 207 B 56 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment ROM Memory Allocation Displays ROM memory allocation Statistics S Memory Usage Data data i bData Pdata
306. nections sbit Button Pin at 0 Declare Button Pins It will be used by Button Library End Button connections bit oldstate Old state flag 1 main 1 255 Configure PORTO as input QxAA Initial PORT2 value do if 17 Detect logical one oldstate 1 Update flag if oldstate amp amp Button 1 0 Detect one to zero transition P2 P2 f invert PORT2 oldstate 0 Update flag while 1 Endless loop 454 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLE MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries CONVERSIONS LIBRARY The mikroC for 8051 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 fol lowing routines ByteToStr ShortToStr WordToStr IntToStr LongToStr LongWordToStr FloatToStr The following functions convert decimal values to BCD and vice versa Dec2Bcd 2 16 Dec2Bcd16 ByteToStr Prototype void ByteToStr unsigned short input char output Description Converts input byte to a string The output string has fixed width of 4 characters including null character at the end string termina tion The output string 15 right justified and remaining positions on the left 1f any are filled
307. ned long int MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 127 CHAPTER 5 Language Reference mikroC for 8051 Decimal Decimal constants from 2147483648 to 4294967295 are allowed Constants exceeding these bounds will produce an Out of range error Decimal constants must not use an initial zero An integer constant that has an initial zero is interpret ed as an octal constant Thus Int i 10 decimal 10 int i 010 decimal 8 int 1 D decimal 0 octai 0 7 In the absence of any overriding suffixes the data type of a decimal constant is derived from its value as shown below Hexadecimal All constants starting with 0x or 0x are taken to be hexadecimal In the absence of any overriding suffixes the data type of an hexadecimal constant is derived from its value according to the rules presented above For example 0xc367 will be treated as unsigned int 128 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference Binary All constants starting with 0b or 08 are taken to be binary In the absence of any overriding suffixes the data type of an binary constant is derived from its value according to the rules presented above For example 0b11101 will be treated as short Octal All constants with an initial zero are taken to be octal If an octal constant contains the illegal digits 8 or 9 an error is report
308. nes Soft Uart Init Soft Uart Read Soft Uart Write 322 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Soft Uart Init Prototype 2 Soft Uart Init unsigned long baud rate char inverted Description 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 Requires Global variables Soft Uart RX receiver pin Soft Uart TX transmiter pin must be defined before using this function Example Initialize Software UART communication on pins Rx IX at YUU bps SOIL Uaft IBNIEISSDSO 9 Soft Uart Read Prototype char Soft Uart Read char error Byte received via UART Description The function receives a byte via software UART This is a block ing function call waits for start bit Parameters error Error flag Error code is returned through this variable Upon successful transfer this flag will be set to zero An non zero value indicates communication error Requires Software UART must be initialized before using this function see the Soft Uart Init routine Example char data int error wait until data is received do data SOLL Uart Read eerror while error Now we can work with data ir Gata esa
309. ng IL 1 2ms 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 1s received synchronization achieved etc External dependencies of Manchester Code Library The following variables must be defined in all projects using Description Example Manchester Code Library extern sbit MANRXPIN Keypad Port sfr char keypadPort at P0 extern sbit MANTXPIN Transmit line sbit MANTXPIN at 1 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD AT CHAPTER 6 Libraries mikroC for 8051 Library Routines Man Receive Init Man Receive Man Send Init Man Send Man Synchro The following routines are for the internal use by compiler only Manchester 0 Manchester 1 Manchester Out Man Receive Init Prototype unsigned int Man Receive Init Returns o if initialization and synchronization were successful 1 upon unsuccessful synchronization Description The function configures Receiver pin and performs synchroniza tion 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 Synchro routine to enable synchronization Requires MANRXPIN variable must be defined before using this fu
310. nion Declaration 167 SZO WOW M 167 Union Member 167 Bit Fields 25545 dha doo ded mri dr ohh ace oe teas de dr ons aed ob die dci ui ac ee 168 Bit Fields Declaration 168 Bit Fields Access 169 Types Conversions 170 Standard Conversions 170 Arithmetic Conversions 171 IIo cuc 171 Pointer Conversions 172 Explicit Types Conversions Typecasting 172 amp E Se ee x 4 173 Declarations and Definitions 173 Declarations and Declarators 174 Eco am ta dow a ale hash ae ak ee a ah 175 Linkage RUIS oi EU Qo Ae madd ee 175 Internal Linkage Rules ccc cee eee 175 External Linkage Rules 176 Storage 176 FUNG
311. nitialize l 1 3 3 1 init 77 dnitialize CANSPIT MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 233 CHAPTER 6 Libraries mikroC for 8051 CANSPI TX MSG FLAGS CANSPI TX MSG FLAGS are flags related to transmission of a CAN message const char CANSPI TX PRIORITY BITS 0x03 CANSPI TX PRIORITY 0 OxFC XXXXXX00 CANSPI TX PRIORITY 1 XXXXXX01 CANSPI TX PRIORITY 2 OxFE XXXXXX10 CANSPI TX PRIORITY 3 OxFF XXXXXX11 CANSPI TX FRAME BIT 0x08 CANSPI TX STD FRAME OxFF XXXXX1XX CANSPI TX XTD FRAME OxF7 XXXXXOXX CANSPI TX RTR BIT 0x40 CANSPI TX NO RTR FRAME OxFF X1XXXXXX CANSPI TX FRAME OxBF XOXXXXXX You may use bitwise AND amp to adjust the appropriate flags For example form value to be used as sending message flag send config CANSPI TX PRIORITY 0 5 CANSPI TX XTD FRAME 6 CANSPI TX NO RTR FRAME CANSPIWNFPILeil10 data 1 pond Contig CANSPI RX MSG FLAGS CANSPI RX MSG FLAGS are flags related to reception of CAN message If a particular bit is set then corresponding meaning is TRUE or else it will be FALSE const char CANSPI RX FILTER BITS 0x07 Use this to access filter bits CANSPI RX FILTER 1 0x00 CANSPI RX FILTER 2 Heol CANSPI RX FILTER 3 Deu CANSPI RX FILTER 4 0x03 CANSPI RX FILTER 5 0x04 CANSPI RX FILTER 6 0x05 CANSPI RX OVERFLOW 0x08 Set if Overflowed else cleared CANSPI RX INVAL
312. nored Results are unpredictable if there are not enough arguments for the format specifications The format specifications have the following format MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 461 CHAPTER 6 Libraries mikroC for 8051 Description 5 flags width precision LII XL D Lb v conver sion Each field in the format specification can be a single character or a number which specifies a particular format option The conver sion type field 1s where a single character specifies that the argu ment is interpreted as a character string number or pointer as shown in the following table Argument conversion type 5 Output Format Signed decimal number u Unsigned decimal number Unsigned octal number Unsigned hexadecimal X unsigned int number using 0123456789abcdef Unsigned hexadecimal X unsigned int number using 0123456789ABCEDF Floating point number double using the format d dddde dd Floating point number E double using the format d dddd E dd Floating point number using either e or f format double whichever is more compact for the specified value and precision int 18 converted to char and the resulting character 1s written 462 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Floating point number double using the format
313. ns Nothing Description The function sets Port Expander s PortA and PortB direction Parameters ModuleAddress Port Expander hardware address see schemat ic at the bottom of this page Direction data to be written to direction registers Data to be written to the PortA direction register are passed in Direction s higher byte Data to be written to the PortB direction register are passed in Direction s lower byte Each bit corresponds to the appropriate pin of the PortA PortB register Set bit designates corresponding pin as input Cleared bit designates corresponding pin as output Port Expander must be initialized See Expander Init Example Set Port Expander s PORTA to be output and PORTB to be input Expander oet DiITGCLtionPOPLAB O 0XQUPEJJ Expander Set PullUpsPortA Prototype void M ser PulllpsPortAichar ModuleAddress char Data Returns Nothing Description The function sets Port Expander s PortA pull up down resistors Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data for choosing pull up down resistors configuration Each bit corresponds to the appropriate pin of the PortA register Set bit enables pull up for corresponding pin Requires Port Expander must be initialized See Expander Init Example Set Port Expander s PORTA pull up resistors Expander Set PUllUDSPOPLA D 292 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SO
314. ns 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 110 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 8051 specific 8051 Memory Organization 8051 Memory Models 8051 Memory Type Specifiers 111 CHAPTER 4 8051 Specifics mikroC for 8051 8051 SPECIFICS Types Efficiency First of all you should know that 8051 ALU which performs arithmetic operations is optimized for working with bytes Although mikroC is capable of handling very complex data types 8051 may choke on them especially if you are working on some of the older models This can dramatically increase the time needed for per forming even simple operations Universal advice is to use the smallest
315. nsigned short y pos unsigned short color Description Draws a dot on GLCD at coordinates pos pos Parameters x pos X position Valid values 0 127 y pos y position Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines a dot state 0 clears dot 1 puts a dot and 2 inverts dot state Note For x and y axis layout explanation see schematic at the bottom of this page GLCD needs to be initialized see Glcd_Init routine Example Invert the dot in the upper left corner Dori Us Glcd Line Prototype void Line int x start int y start int x end int y end unsigned short color Description Draws a line on GLCD Parameters x start X coordinate of the line start Valid values 0 127 y start y coordinate of the line start Valid values 0 63 x end X coordinate of the line end Valid values 0 127 y end y coordinate of the line end Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the line color 0 white 1 black and 2 inverts each dot GLCD needs to be initialized see Gled Init routine Example Draw a line between dots 0 0 and 20 30 Llneto D 40 20 LI MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 249 CHAPTER 6 Libraries mikroC for 8051 Glcd V Line Prototype void Glcd V Line unsigned short y start unsigned short y end un
316. nt The Macro offers the following commands Starts recording keystrokes for later playback de Stops capturing keystrokesthat was started when the Start Recordig command was selected Allows a macro that has been recorded to be replayed Related topics Advanced Code Editor Code Templates MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 59 CHAPTER 2 Environment mikroC for 8051 INTEGRATED TOOLS USART Terminal The mikroC for 8051 includes the USART communication terminal for RS232 com munication You can launch it from the drop down menu Tools USART Terminal or by clicking the USART Terminal Icon from Tools toolbar RS232 Terminal Settings Communication Com Port Echo Send Send File Baud Append CR Send as typing Start Logging Stop Bits LJ LF 1 Send as number Caer Parity Format xi ASCII C HEX O DEC Data bits Connected to COM1 ET Sent Echo Commands RIS Off USART Terminal Status Send CTS DSR e Log Files Read from Write to 60 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment ASCII Chart The ASCII Chart is a handy tool particularly useful when working with LCD dis play You can launch it from the drop down menu Tools ASCII chart or by click ing the View ASCII Chart Icon A from Tools toolbar Ascii Chart NUL
317. ntation 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 15 owned by mikroElektronika Associates and 15 protected by 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 attempt to reverse engineer decom pile or disassemble it except and only to the extent that such activity 15 expressly permitted by applicable law notwithstanding this limitation 4 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroC for 8051 Introduction If you have purchased an upgrade version of Software it constitutes a single prod uct with the mikroElektr
318. ntil the function reaches a character which it doesn t recognize including a null character div Prototype div t div int number int denom Description Function computes the result of division of the numerator number by the denominator denom the function returns a structure of type div t comprising quotient quot and remainder rem see Div Structures MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 445 CHAPTER 6 Libraries mikroC for 8051 Idiv Prototype ldiv t ldiv long number long denom Description Function is similar to the div function except that the arguments and result structure members all have type long Function computes the result of division of the numerator number by the denominator denom the function returns a structure of type 1 t comprising quotient quot and remainder rem see Div Structures uldiv Prototype uldiv_t uldiv unsigned long number unsigned long denom Description Function is similar to the div function except that the arguments and result structure members all have type unsigned long Function computes the result of division of the numerator number by the denominator denom the function returns a structure of type uldiv t comprising quotient quot and remainder rem see Div Structures labs ERISQUE long labs long x ae returns the absolute 1 e positive value of long integer int max int a int b Func
319. nts stored in di for degree exp Description Function returns the value of e the base of natural logarithms raised to the power 1 fabs Prototype Function returns the absolute 1 e positive value of a floor Prototype double floor double x Description Function returns the value of parameter x rounded down to the nearest integer MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 441 CHAPTER 6 Libraries mikroC for 8051 frexp Prototype double frexp double value int eptr Description Function splits a floating point value into a normalized fraction and an integral power of 2 The return value is the normalized fraction and the integer exponent is stored in the object pointed to by pEr Idexp Prototype double ldexp double value int newexp Function returns the result of multiplying the floating point num ber num by 2 raised to the power n 1 e returns x 2 Prototype double log double x Description Function returns the natural logarithm of x 1 Log x log10 Prototype double 10410 double x Description Function returns the base 10 logarithm of i e 10910 x modf Prototype double double val double iptr Description Returns argument vai split to the fractional part function return val and integer part in number iptr OW Prototype double pow double x double y Descript
320. null character A null string 1s stored as a single null character The characters inside the double quotes can include escape sequences This code for example t Name tAddress n n prints like this Name N Address The Name is preceded by two tabs The Address is preceded by one tab The line is followed by two new lines The provides interior double quotes The escape character sequence is translated into by the compiler Adjacent string literals separated only by whitespace are concatenated during the parsing phase For example This is just an example is equivalent to This is just an example Line Continuation with Backslash You can also use the backslash as a continuation character to extend a string constant across line boundaries This is really a one line string 132 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference ENUMERATION CONSTANTS Enumeration constants are identifiers defined in enun type declarations The identi fiers are usually chosen as mnemonics to contribute to legibility Enumeration con stants are of int type They can be used any expression where integer constants are valid For example enum weekdays SUN 0 MON TUE WED THU FRI SAT The identifiers enumerators used must be unique within the scope of the enum dec laration Negative initializers are allowed See
321. obals and static objects must be constants or constant expres sions The initializer for an automatic object can be any legal expression that evalu ates to an assignment compatible value for the type of the variable involved Scalar types are initialized with a single expression which can optionally be enclosed in braces The initial value of an object is that of the expression the same constraints for type and conversions as for simple assignments are applied to initial izations too For example int i 1 char s hello Struct complex o 19 1 0 4 j where complex is a structure float float For structures or unions with automatic storage duration the initializer must be one of the following An initializer list single expression with compatible union or structure type In this case the initial value of the object 1s that of the expression 180 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference For example struct dot int x int y m 30 40 For more information refer to Structures and Unions Also you can initialize arrays of character type with a literal string optionally enclosed in braces Each character in the string including the null terminator ini tializes successive elements in the array For more information refer to Arrays Automatic Initialization The mikroC for 8051 does not provide automatic initializati
322. of different type if an expression following the keyword return does not match the declared function return type if intializing an object in declaration with an object of different type In these situations compiler will provide an automatic implicit conversion of types without any programmer s interference Also the programmer can demand conver sion explicitly by means of the typecast operator For more information refer to the Explicit Typecasting STANDARD CONVERSIONS Standard conversions are built in the mikroC for 8051 These conversions are per formed automatically whenever required the program They can also be explicit ly required by means of the typecast operator refer to the Explicit Typecasting The basic rule of automatic implicit conversion 15 that the operand of simpler type is converted promoted to the type of more complex operand Then the type of the result is that of more complex operand 170 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference Arithmetic Conversions When using arithmetic expression such as a b where a and b are of different arithmetic types the mikroC for 8051 performs implicit type conversions before the expression 15 evaluated These standard conversions include promotions of lower types to higher types in the interests of accuracy and consistency Assigning a signed character objec
323. oint number representation Write message on UART MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 465 CHAPTER 6 Libraries mikroC for 8051 sprintf buffer 12e ww Format ww and store It to buffer UartWriteConstText Xrine format Write message on UART UartWriteText buffer Write buffer on UART sprintf buffer 125 ww Format ww and store it to buffer UartWriteconstTextiO rint fotmat Write message on UART UartWriteText buffer Write buffer on UART sprintf buffer 12g ww Format ww and store it to buffer UartWriteConstText r ng format Write message on UART UartWriteText buffer Write buffer on UART 466 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries TIME LIBRARY The Time Library contains functions and type definitions for time calculations in the UNIX time format which counts the number of seconds since the epoch This is very convenient for programs that work with time intervals the difference between two UNIX time values is a real time difference measured in seconds What 15 the epoch Originally it was defined as the beginning of 1970 GMT January 1 1970 Julian day GMT Greenwich Mean Time 15 a traditional term for the time zone in England The TimeStruct type is a structure type suitable for time and date storage Type dec laration is contained in timelib h which can
324. on Function locates the first occurrence of the string s2 in the string 51 excluding the terminating null character The function returns pointer to first occurrence of s2 in s1 if no string was found function returns 0 If s2 15 a null string the function returns 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 451 CHAPTER 6 Libraries mikroC for 8051 Strcspn Prototype char strcspn char sl char s2 function returns 0 Description Function locates the first occurrence of the string s2 in the string 51 excluding the terminating null character The function returns pointer to first occurrence of s2 in 51 if no string was found function returns 0 If s2 1s a null string the Strpbrk Prototype char strpbrk char sl char 52 Description Function searches si for the first occurrence of any character from the string s2 The terminating null character 1s not included in the search The function returns pointer to the matching charac ter in s1 If si contains no characters from s2 the function returns 0 Strrchr Prototype char strrchr char ptr unsigned int chr Description Function searches the string ptr for the last occurrence of charac ter chr The null character terminating ptr is not included in the search The function returns pointer to the last chr found in ptr if no matching character was found function returns 0 452 MIKROELEKTRONIKA SOFTWARE
325. on The function sets Port Expander s PortA direction Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written to the PortA direction register Each bit corresponds to the appropriate pin of the PortA register Set bit designates corresponding pin as input Cleared bit designates corresponding pin as output Port Expander must be initialized See Expander Init Example Set Port Expander s PORTA to be output Expander Set DirsoctionPOFEA D 0x00 2 Expander Set DirectionPortB Prototype void set ModuleAddress char Data Description The function sets Port Expander s PortB direction Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page bata 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 Set DirectionPOrtBi i0 0xFEPJ MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 291 CHAPTER 6 Libraries mikroC for 8051 Expander_Set_DirectionPortAB Prototype void Expander Set mela ak ModuleAddress unsigned int Direction Retur
326. on about greediness Greedy takes as many as possible non greedy takes as few as possible For example and b applied to string abbbbc return bbbb returns b b returns empty string b 2 3 returns b 2 3 J returns bbb Metacharacters Alternatives You can specify a series of alternatives for a pattern using to separate them so that fee fie foe will match any of fee fie or foe in the target string as would e i o e The first alternative includes everything from the last pattern delimiter or the beginning of the pattern up to the first and the last alternative contains everything from the last to the next pattern delimiter For this reason it s common practice to include alternatives in parentheses to min imize 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 1s the first alternative tried and it successfully matches the target string this might not seem important but it 1s important when you are capturing matched text using parentheses Also remember that is interpreted as a literal within square brackets so if you write fee You re really only mat
327. on for objects Uninitialized globals and objects with static duration will take random values from memory FUNCTIONS Functions are central to C programming Functions are usually defined as subpro grams which return a value based on a number of input parameters Return value of the function can be used in expressions technically function call is considered to be an expression like any other C allows a function to create results other than its return value referred to as side effects Often the function return value is not used at all depending on the side effects These functions are equivalent to procedures of other programming lan guages such as Pascal C does not distinguish between procedure and function functions play both roles Each program must have a single external function named main marking the entry point of the program Functions are usually declared as prototypes in standard or user supplied header files or within program files Functions have external linkage by default and are normally accessible from any file in the program This can be restricted by using the static storage class specifier in function declaration see Storage Classes and Linkage Note Check the 8051 Specifics for more information on functions limitations on the 8051 compliant micros MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 181 CHAPTER 5 Language Reference mikroC for 8051 Function Declaration
328. on was not successful Half of the manchester bit length given in multiples of 10us upon successful synchronization Description Measures half of the manchester bit length with 10us resolution Requires To use this function you must first prepare MCU for receiv ing See Man Receive Init Example unsigned int man half bit len man half bit len Man 5ynchrot Library Example The following code is code for the Manchester receiver it shows how to use the Manchester Library for receiving data ff LCD modulis connections sbit LCD RS at 2 0 sbit LCD EN at 2 1 shit LCD DT PZ B5 sbit LCD D6 at P2 B4 shit LCD at PZ B3 280 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries sbit LCD D4 at P2 B2 End LCD module connections Manchester module connections sbit MANRXPIN at PO BO sbit MANTXPIN at P1 B1 End Manchester module connections char error ErrorCount temp void main LErrorcounr Q Led initis ff Initialize LCD Lcd LCD CLEAR Clear LCD display Man Receive Initialize Receiver while 1 44 Endless loop Lcd Cmd LCD FIRST ROW Move cursor to the ist row while 1 Wait for the start byte temp Man Receive amp error Attempt byte receive if temp 0 Start byte see Transmitter example break We got the starting sequence if error
329. onMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPI module mast be in config mode for baud rate settings can config flags CANSPI CONFIG SAMPLE THRICE amp CANSPI CONFIG PHSEG2 PRG ON amp CANSPI CONFIG STD MSG amp CANSPI CONFIG DBL BUFFER ON amp CANSPI CONFIG VALID XTD MSG amp CANSPI CONFIG LINE FILTER OFF DCANSEPISSLtBARUOBRTOTl l 3 2 1 conrig T1845 CANSPISetMask Prototype void CANSPISetMask char CAN MASK long val char CAN CONFIG FLAGS Description Configures mask for advanced filtering of messages The parame ter value is bit adjusted to the appropriate mask registers Parameters CAN MASK CANSPI module mask number Valid values CANSPI MASK constants see CANSPI constants val mask register value CAN CONFIG FLAGS selects type of message to filter Valid values CANSPI CONFIG ALL VALID MSG CANSPI CONFIG MATCH MSG amp CANSPI CON FIG STD MSG CANSPI CONFIG MATCH MSG amp CANSPI CON FIG XTD MSG see CANSPI constants 228 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Requires CANSPI module must be in Config mode otherwise the function will be ignored See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CAN SPI Extra Board or similar hardware See connection example
330. onds delay function J rmitialise C OD 27 Clear CLOD 44 Draw image Draw box Draw rectangle Draw line 256 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries delay2S foriii 11 lt 607 H Draw horizontal and vertical lines Delay ms 250 Glod 7 0812 24 11 12 H biteiz 120 22 11 1 25 Glod FXLL UxOU Glod Font haracterboxb B 9 32 77 Choose font ses _ Lib GLODPOonts co in Uses folder Gled Write TexL UmLETOR U 5y 7 4 Write string for ii 1 ii lt 10 1153 Draw circles Glod hs acy 2511 17 1 25 Boxil12 20 70 27 2 44 Draw box 1 25 Gled Set Font Fontoystenox2 5 8 32 Change font someText BIG ONE Glcd Write Text someText 5 3 2 Write string 1 25 someText SMALL NOT SMALLER Glcd Write Text someText 20 5 1 Write String 1 25 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 297 CHAPTER 6 Libraries mikroC for 8051 HW Connection o Leftside Right side X AXIS x 0 63 x 0 63 VCC Vee Contrast vec Adjustment Vo 64 085681 OSCILLATOR 6 2 GLCD HW connection 258 MIKROELEKTRONIKA S
331. onika Associates software that you upgraded You may use the upgrade version of Software only in accordance with the License Agreement LIMITED WARRANTY Respectfully excepting the Redistributables which are provided as 15 without warranty of any kind mikroElektronika Associates warrants that Software once updated and properly used will perform substantially in accordance with the accom panying 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 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 EXTENT PERMITTED BY APPLICABLE LAW MIKROELEKTRONIKA ASSOCIATES AND ITS SUPPLIERS DISCLAIM
332. operly connected to mikroElektronika s CAN SPI Extra Board or similar hardware See connection example at the bottom of this page Example set the appropriate filter value and message type CANSPISertOperationMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPI module must be config mode for filter settings Bet id af filter BI to 2 CANSPISetFilter CANSPI FILTER B1 F1 3 CANSPI CON FIG XTD MSG CANSPIRead Prototype char CANSPIRead long 14 char rd data char data len char RX MSG FLAGS Returns O if nothing is received 0xFF 1f one of the Receive Buffers is full message received Description If at least one full Receive Buffer is found it will be processed in the following way Message ID 15 retrieved and stored to location provided by the id parameter Message data is retrieved and stored to a buffer provided by the rd 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 parameter 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 230 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Requires
333. or 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 92 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Stopwatch Cycles Time p DN 214 r keset To Zero RAM Window The Software Simulator RAM Window is available from the drop down menu View gt Debug Windows gt RAM The RAM Window displays a map of MCU s RAM with recently changed items colored red You can change value of any field by double clicking it F 8 s sis 888888888888 81 8 00 00 00 00 00 888858288 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 93 CHAPTER 2 Environment mikroC for 8051 SOFTWARE SIMULATOR OPTIONS Start Software Simulator Run Pause Debugger Run or pause Software Simulator Stop Software Simulator Toggle breakpoint at the current cursor position To view all TOGGLE breakpoints select Run gt View Breakpoints from the drop down menu Double clicking an item in th
334. orries 417 T6969C CWE suu d cicer doo iene qtu dee dos c d dea ded do oed ded 417 169696 nro 418 3 x2 9 3 418 TO953C Set CUSO a 252 12 eae e ees pote Sa C 419 6963 _ 419 TO9SD3C passe ste Senses gt 420 1222504 APRES SG RSS ESQ EG 420 T6963C 421 T6963C DisplayTxiPanel 421 T6963C SetGrPanel 422 T6963C SetIxtPanel 422 169630 dau autos zwar dod ee eas db Da eae oad 423 Io Oli MP 423 12 550 MP 424 TO965C Cursor Height uou d 424 T6963C Graphics 425 TOSDSC 13 wute xoci da nee eee ees ees 425 T6959 CU SOL Roda 426 T6963C Cursor 426 Library 426 HW Connection 431 VART CIDA esene assenar er See EA PESE EE EE 432 Library ROUNNCS RE 432 wee eed 432 Uart Data _Ready 433 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIO
335. ose to go with the putString defini tion above the define line below should be commented out define Spi Ethernet putString SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 349 CHAPTER 6 Libraries mikroC for 8051 this function is called by the library the user accesses to the HTTP request by successive calls to Ethernet getByter the user puts data the transmit buffer successive calls to Spi Ethernet puthyte the function must return the length in bytes of the HTTP reply pr 0 Xf nothing to transmit if you don t need to reply to HTTP requests just define this function with a return 0 as single statement 6 X e unsigned int Spi Ethernet UserTCP unsigned char remoteHost unsigned int remotePort unsigned int localPort unsigned int reqLength idata unsigned int len my reply length if localPort 80 I listen only to web request on port 80 return O 44 get 10 first bytes only of the request the rest does not matter here for len 0 len lt 10 1 te opi Ethernet getByte M 0 len 0 if memcmp getRequest httpMethod 5 only GET method is supported here return O httpCounter one more request done if getRequest 5 s if request path name starts with s store dynamic data in transmit buffer the text string
336. oshiba GLCD module needs to be initialized See Spi T6963C Config routine Example 5 6963 Box 0 119 239 127 T6963C WHITE MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 393 CHAPTER 6 Libraries mikroC for 8051 Spi T6963C Image void Spi T6963C Image const code char pic Description bitmap on GLCD Parameters pic image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroC for 8051 pointer to const and pointer to RAM equivalency Use the mikroC s integrated GLCD Bitmap Editor menu option Tools GLCD Bitmap Editor to convert image to a constant array suitable for displaying on GLCD Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Spi T6963C Sprite Prototype void Spi T6963C Sprite unsigned char px unsigned char py const char pic unsigned char sx unsigned char sy Description Fills graphic rectangle area to pxtsx pytsy with cus tom size picture Parameters px X coordinate of the upper left picture corner Valid values multiples of the font width py y coordinate of the upper left picture corner pict picture to be displayed sx picture width Valid values multiples of the font width sy picture height Note If px and sx parameters are not multiples of the font width they will be scaled to the nearest lower number that is a multiple o
337. ototype void Soft Spi Write char sdata Description This routine sends one byte via the Software SPI bus Parameters sdata data to be sent Requires Soft SPI must be initialized before using this function See Soft Spi Init routine Example Write a byte to the Soft SPI bus Sort Spi WriteiDxAA MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 319 CHAPTER 6 Libraries mikroC for 8051 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 con verter DAC module connections Chip Select P3 B4 CLI St sbit SoftSpi SDI at 1 6 sbit SoftSpi SDO at P1 B5 End DAC module connections unsigned int value void InitMain pO 255 Set PORTO as input Soft SPI inte ff Initialize Soft DAC increments 0 4095 gt output voltage 0 Vref void DAC Output unsigned int valueDAC char temp Chip Select 0 Select DAC chip Send High Byte temp valueDAC gt gt 8 amp OxOF Store valueDAC 11 8 to temp 3 0 temp 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 74 Deselect
338. otype Char Uart Read Received byte Description The function receives a byte via UART Use the Uart Data Ready function to test if data is ready first Requires MCU with the UART module The UART module must be initialized before using this routine See Uart Init routine Example char receive read data if ready if Uart Data Ready receive Part React MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 433 CHAPTER 6 Libraries mikroC for 8051 Uart_Write Description The function transmits a byte via the UART module Parameters TxData data to be sent Requires MCU with the UART module The UART module must initialized before using this routine See Uart Init routine Example char data 1 Library Example This example demonstrates simple data exchange via UART If MCU is connected to the PC you can test the example from the mikroC for 8051 USART Terminal char wart rd void main Uart init 4800 Initialize UART module at 4800 bps Delay 18100 Wait for UART module to stabilize while 1 Endless loop Uart Data Ready 1 Check if UART module has received data uart rd Uart Read Read data Uart Write uart rd Send the same data back 434 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries HW Connection SUB D 9p Receive mot CONNECT MCU
339. pdata Description Paged 256 bytes external data memory accessed by opcode MOVX Rn This memory is indirectly accessed using 8 bit addresses and is one 256 byte page of external data RAM of the 8051 The amount of pdata 15 limited size to 256 bytes Example puts x in date ram unsigned char data x Related topics 8051 Memory Organization Memory models Accessing individual bits SFRs Constants Functions 120 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER mikroC for 8051 Language Reference Lexical Elements 121 CHAPTER 5 Language Reference mikroC for 8051 MIKROC LANGUAGE REFERENCE LEXICAL ELEMENTS OVERVIEW The following topics provide a formal definition of the mikroC for 8051 lexical ele ments They describe different categories of word like units tokens recognized by the mikroC for 8051 In the tokenizing phase of compilation the source code file is parsed that is bro ken down into tokens and whitespace The tokens in the mikroC for 8051 are derived from a series of operations performed on your programs by the compiler and its built in preprocessor 122 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference WHITESPACE Whitespace is a collective name given to spaces blanks horizontal and vertical tabs newline characters and comments Whitespace can serve to indicate where tokens start a
340. perature is negative if temp2write amp 0 8000 text 0 temp2write temp2write 1 extract temp whole temp whole tempewrite gt gt SHIFT f Convert temp whole to characters if temp whole 100 text 0 temp whole 100 48 text 1 temp whole 10 10 48 Extract tens digit text 2 temp whole 10 48 Extract ones digit extract temp fraction and convert it fo unsigned int temp Traction tempo2write lt lt 4 SHIFT temp Traction lt Ux00UF Lemp Erection 820 Convert temp fraction fto characters 4 temp fraction 1000 48 Extract thousands digit text 5 temp fraction 100 10 48 Extract hundreds digit text 6 temp fraction 10 10 48 Extract tens digit 7 temp fraction 10 4B JU Extract ones dioit print temperature on LCD Oui 2 Text void main Led Init ff Lcd LCD CLEAR Clear LCD Led Cm Co CURSOR OFF 77 Turn cursor off Log 1 Temperature 2 I Print degree character C for Centigrades Logd Chri2 13 223 5 274 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 main loop do perform temperature Ow Ow Write 0xCC Ow Write 0x44 Delay usil20 Ow Reset Ow Wei Ux CG Ow Write CHAPTER 6 Libraries read
341. ple unsigned t 437 char txt 6 WordToBtri t txt 44 txt is 437 two blanks here 456 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 IntToStr Prototype CHAPTER 6 Libraries void IntToStr int input char output Description Converts input signed integer number to a string The output string has fixed width of 7 characters including null character at the end string termination The output string 1s right justified 2 remaining positions on the left if any are filled with anks Parameters input signed integer number to be converted output destination string Destination string should be at least 7 characters in length Example LongToStr Prototype int j 4220 char txt 7 IntToBtri txt J txt is 1220 one Blank here void LongToStr long input char output Description Converts input signed long integer number to a The output C string has fixed width of 12 characters including null character at the end string termination The output string is right justified and the remaining positions on the left 1f any are filled with blanks Parameters input Signed long integer number to be converted output destination string Destination string should be at least 12 characters in length Example long jj 3700000 char txt 12 11 is Y 3700000 three blan
342. pression must evaluate to integral type While expected but gt s found Void func cannot return values continue outside of loop Unreachable code Label redefined Void type in expression Too many chars Unresolved type Arrays of objects containing zero size arrays are illegal Invalid enumerator ILevel can be used only with interrupt service routines ILevel value must be integral constant ILevel out of range 0 4 expected but ss found expected but gt s found break outside of loop or switch Empty char Nonexistent field 551 Illegal char representation 5 Initializer syntax error multidimension array missing subscript Too many initializers of subaggregate At least one Search Path must be specified 88 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Not enough RAM for call satck Parameter gt s must not be of bit or sbit type Function must not have return value of bit or sbit type Redefinition of 251 already defined in 551 Main function is not defined System routine not found for initialization of 551 Bad agregate definition 251 Unresolved extern 55 Bad function absolute address 5251 Not enough RAM 55 Compilation Started Compiled Successfully Finished with errors 01 Mar 2008 14 22 26
343. projectfiles Cancel Device MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD TJ CHAPTER 2 Environment mikroC for 8051 Step Three enter the oscillator frequency value New P roject Wizard Step 2 6 Setup the clock for example 11 0592 MHz Device Clock MHz Cancel Step Four Select the desired memory model Choose one of the available memory models Memory Model 2 Smal Compact Large 78 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Step Five Specify the location where your project will be saved New Project Wizard Project File Name a Projects iFirstProjectiFirstProject m Step Six 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 Add File To Project D Projects FirstProject Definit h File Name D Projects FirstProject Definit h Remove Remove All Back Related topics Project Manager Project Settings Memory Model MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 79 CHAPTER 2 Environment mikroC for 8051 CUSTOMIZING PROJECTS Edit Project You can change basic project settings in the Project S
344. quipment hazardous environments requiring fail safe performance such as in the operation of nuclear facilities aircraft navigation or communication systems air traffic control direct life support machines or weapons systems in which the failure of Software could lead directly to death personal injury or severe physical or environmental damage High Risk Activities mikroElektronika Associates and its suppliers specifically disclaim any expressed or implied warranty of fitness for High Risk Activities GENERAL PROVISIONS This statement may only be modified in writing signed by you and an authorised officer of 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 pur pose all limitations of liability and exclusions of damages set forth in the Limited Warranty shall remain in effect This statement gives you specific legal rights you may have others which vary from country to country mikroElektronika Associates reserves all rights not specif ically granted in this statement 6 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroC for 8051 Introduction mikroElektronika Visegradska 1 11000 Belgrade Europe Phone 381 11 36 28 830 Fax 381 11 36 28 831 Web www mikroe com E mail office mik
345. r any of them was called or not Note The pragma unca11 directive can help the linker to optimize function frame allocation in the compiled stack BUILT IN ROUTINES The mikroC for 8051 compiler provides a set of useful built in utility functions The Lo 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 1 code is gen erated in the place of a call so the call doesn t count against the nested call limit vdelay ms Delay Cyc and Get kHz are actual C routines Their sources can be found in Delays c file located in the uses folder of the compiler Lo Delay us Clock Khz Hi Delay ms Clock Mhz Higher Vdealy ms Get Fosc khz Highest Delay Cyc MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 103 CHAPTER 3 Specifics mikroC for 8051 Lo Lowest 8 bits byte of number bits 7 0 Description Function returns the lowest byte of number Function does not interpret bit patterns of number it merely returns 8 bits as found in register This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Requires Arguments must be variable of scalar type 1 Arithmetic Types and Pointers
346. r character values The mikroC for 8051 supports integer constants floating point constants character constants string constants strings literals enumeration constants The data type of a constant is deduced by the compiler using such clues as a numer ic value and format used in the source code INTEGER CONSTANTS Integer constants can be decimal base 10 hexadecimal base 16 binary base 2 or octal base 8 In the absence of any overriding suffixes the data type of an inte ger constant is derived from its value Long and Unsigned Suffixes The suffix or 1 attached to any constant forces that constant to be represented as long Similarly the suffix u or u forces a constant to be unsigned Both and v suffixes can be used with the same constant in any order or case ul Lu UL etc In the absence of any suffix v u L or 1 a constant is assigned the smallest of the following types that can accommodate its value short unsigned short lnt unsigned int long int unsigned long int Otherwise If a constant has the U suffix its data type will be the first of the following that can accommodate its value unsigned short unsigned int unsigned long int If a constant has the L suffix its data type will be the first of the following that can accommodate its value 1ong int unsigned long int If a constant has both L and U suffixes LU or UL its data type will be unsig
347. raries T6963C Write Text Prototype void T6963C Write Text unsigned char str unsigned char x unsigned char y unsigned char mode Description Writes text in the current text panel of GLCD at coordinates x y Parameters str text to be written x text position on x axis y text position on y axis node mode parameter Valid values T6963C ROM MODE OR T6963C ROM MODE XOR T6963C ROM MODE AND and T6963C ROM MODE TEXT Mode parameter explanation OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combining text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are com bined via the logical exclusive OR This can be useful to dis play Mig in the negative mode 1 white text on black back round 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 text The Text Attribute values are stored the graphic area of display memory For more details see the T6963C datasheet Requires Toshiba GLCD module needs to be initialized See the T6963C_ Init routine Example 16963C_Write Text GLCD LIBRARY DEMO WELCOME 0 0 T6963C ROM MODE XOR MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 415 CHAPTER 6 Libraries mikroC for 8051 T6963C
348. rations Void Type 146 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference ARITHMETIC TYPES The arithmetic type specifiers are built up from the following keywords void char int float and double together with the prefixes short long signed and unsigned From these keywords you can build both integral and floating point types Integral Types The types char and int together with their variants are considered to be integral data types Variants are created by using one of the prefix modifiers short long signed and unsigned In the table below is an overview of the integral types keywords in parentheses can be and often are omitted The modifiers signed and unsigned can be applied to both char and int In the absence of the unsigned prefix signed 1s automatically assumed for integral types The only exception is char which is unsigned by default The keywords signed and unsigned when used on their own mean signed int and unsigned int respective ly The modifiers short and long can only be applied to int The keywords short and long used on their own mean short int and long int respectively unsigned short int jus ies Med unsigned long int MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 147 CHAPTER 5 Language Reference mikroC for 8051 Floating point Types The types float and double together with the long
349. rators with constant integer values black 0 red 1 In the mikroC for 8051 a variable of an enumerated type can be assigned any value of the type int no type checking beyond that is enforced That 15 red OK 1 Also OK means the same With explicit integral initializers you can set one or more enumerators to specific values The initializer can be any expression yielding a positive or negative integer value after possible integer promotions Any subsequent names without initializ ers will be increased by one These values are usually unique but duplicates are legal The order of constants can be explicitly re arranged For example MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 149 CHAPTER 5 Language Reference mikroC for 8051 enum colors black value O0 red value 1 green value 2 blue 6 value 6 violet value 7 white 4 value 4 Initializer expression can include previously declared enumerators For example in the following declaration enum memory sizes bat 1 nibble 4 bit byte 2 nibble kilobyte 1024 byte nibble would acquire the value 4 byte the value 8 and kilobyte the value 8192 Anonymous Enum Type In our previous declaration the identifier colors is an optional enumeration tag that be used subsequent declarations of enumeration variables of the enum colors type enum colors bg border declare v
350. rce a to unsigned int unsigned int a Following line will coerce a to double then coerce b to double automatically resulting in double type value double a b equivalent to double a b 172 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference DECLARATIONS A declaration introduces one or several names to a program it informs the compil er what the name represents what its type 15 what operations are allowed with it etc This section reviews concepts related to declarations declarations definitions declaration specifiers and initialization The range of objects that can be declared includes Variables Constants Functions Types Structure union and enumeration tags Structure members Union members Arrays of other types Statement labels Preprocessor macros Declarations and Definitions Defining declarations also known as definitions beside introducing the name of an object also establish the creation where and when of an object that is the alloca tion of physical memory and its possible initialization Referencing declarations or just declarations simply make their identifiers and types known to the compiler Here 15 an overview Declaration 15 also a definition except if it declares a function without specifying its body it has the extern specifier and has no initializator or body i
351. re sum marized in the table below Intel HEX Intel style hex records Use this file to pro gram 8051 MCU mikro Compiled Library Binary distribu tion of application that can be included in Binary other projects Overview of 8051 memory allotment List File instruction addresses registers routines and labels Human readable assembly with symbolic Assembler File 2 asm names extracted from the List File ASSEMBLY VIEW After compiling the program in the mikroC for 8051 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 a new tab window Assembly is human readable with symbolic names Related topics Project Menu Project Toolbar Error Window Project Manager Project Settings MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 95 CHAPTER 2 Environment mikroC for 8051 ERROR MESSAGES COMPILER ERROR MESSAGES Syntax Error expected 251 but 5 found Array element cannot be a function Function cannot return array Inconsistent storage class Inconsistent type 55 tag redefined 551 Illegal typecast 551 s 15 not a valid identifier Invalid statement Constant expression required Internal error Too many actual parameters Not enough parameters Invalid expresion Identifier expected but 2 1 found
352. reads byte from Port Expander Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page RegAddress Port Expander s internal register address Requires Port Expander must be initialized See Expander Init Example Read a byte from Port Expander s register char read data read data Expander Bead Byte 0 1 Expander_Write_Byte Prototype void Expander Write T indc ModuleAddress char RegAddress char Data Description Routine writes a byte to Port Expander Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page RegAddress Port Expander s internal register address Data data to be written Requires Port Expander must be initialized See Expander Init Example Write a byte to the Port Expander s register Expander Write Byteild l 9EPJ 256 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Expander Read PortA Prototype char Expander Read PortA char ModuleAddress Byte read Description The function reads byte from Port Expander s PortA Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Requires Port Expander must be initialized See Expander Init Port Expander s PortA should be configured as input See Expander Set DirectionPortA and Expander Set DirectionPortAB routines Example Read a
353. rence between the first differing characters in a left to right evaluation Accordingly the result 1s greater than zero if the object pointed to by 51 1s greater than the object pointed to by s2 and vice versa memcpy Prototype void memcpy void dl void 51 int n Description Function copies n characters from the object pointed to by s2 into the object pointed to by If copying takes place between objects that overlap the behavior 1s undefined The function returns address of the object pointed to by a1 memmove Prototype void memmove void to void from register int n Description Function copies n characters from the object pointed to by from into the object pointed to by to Unlike memcpy the memory areas to and from may overlap The function returns address of the object pointed to by to memset Prototype void memmove void to void from register int n Description Function copies the value of the character into each of the first n characters of the object pointed by The function returns address of the object pointed to by p1 strcat Prototype char strcat char char from Description Function appends a copy of the string from to the string to over writing the null character at the end of to Then a terminating null character 1s added to the result If copying takes place between objects that overlap the behavior is undefined to string must have enough sp
354. replied by this request can be interpreted as javascript statements by browsers 350 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 CHAPTER 6 Libraries len putConstString httpHeader HTTP header len putConstString httpMimeTypeScript with text MIME type 4 4 P3 value buttons to reply len putConstString var P3 WorgdTostr Ps dyna len putString dyna len putConstString j add PO value LEDs to reply len putConstString var WorgTostr P0 dyna 2 len putString dyna len putConstString add HTTP requests counter to reply WordToSrtri ihLtp ounter dyna len putConstString var REQ len putString dyna len putConstString else if getRequest 5 t if request path name starts with t toggle P3 LED bit number that comes after unsigned char bitMask 0 for bit mask if 1541911 getRequest 6 77 if 0 lt bit number lt 9 bits 9 does not exist but does not matter bitMask getRequest 6 O convert ASCII to integer bitMask 1 lt lt bitMask create bit mask P3 bitMask toggle P3 with xor operator if len 0 what do to by default len putConstString httpHeader HTTP header len putConstString httpMimeTypeHTML with HTML MIME typ MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS F
355. riginally declared to be pointing to void You can assign the void pointer to the non void pointer refer to void for details Null Pointers A null pointer value is an address that 1s guaranteed to be different from any valid pointer in use in a program Assigning the integer constant 0 to a pointer assigns a null pointer value to it For example int pn 0 Here s one null pointer We can test the pointer like this if pn wee The pointer type pointer to void must not be confused with the null pointer The declaration void vp MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 155 CHAPTER 5 Language Reference mikroC for 8051 declares that vp is a generic pointer capable of being assigned to by any pointer to type value including null without complaint Assignments without proper casting between a pointer to t ype1 and a pointer to type2 where typel and type2 are different types can invoke a compiler warning or error If type1 is a function and type2 isn t or vice versa pointer assignments are illegal If type1 is a pointer to void no cast is needed If type2 is a pointer to void no cast 1s needed FUNCTION POINTERS Function Pointers are pointers variables which point to the address of a func tion 44 Define a function pointer Ant pL2PuncLion float char char Note Thus functions and function pointers with different calling
356. rns 1 if the bits are complementary otherwise returns 0 cards the far left bit and assigns 0 to the far right bit bitwise shift right moves the bits to the right discards the far right bit and if unsigned assigns 0 to the far left bit otherwise sign extends 192 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference Bitwise operators and perform logical operations on the appropriate pairs of bits of their operands Operator complements each bit of its operand For exam ple 1234 amp 0x5678 equals xI230 because 0x1234 0001 0010 0011 0100 4 DIUI V110 ULIL 1000 amp 0001 0010 0011 0000 gt that is xlZ30 7 Similarigr 0412343 Dx23578 equals Ox567C xlz34 Ux3579j 7 Dxl2343 equals OxEDCB Note Operator can also be a pointer reference operator Refer to Pointers for more information Bitwise Shift Operators Binary operators lt lt and gt gt move the bits of the left operand by a number of posi tions specified by the right operand to the left or right respectively Right operand has to be positive With shift left lt lt far left bits are discarded and new bits on the right are assigned zeroes Thus shifting unsigned operand to the left by n positions 15 equiv alent to multiplying it by 2 if all discarded bits are zero
357. roe com 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 devel opment of the mikroC for 8051 are always appreciated feel free to drop a note or two on our Wishlist In our Knowledge Base www mikroe com en kb you can find the answers to Frequently Asked Questions and solutions to known problems If you can not find the solution to your problem in Knowledge Base then report it to Support Desk www mikroe com en support In this way we can record and track down bugs more efficiently which is in our mutual interest We respond to every bug report and ques tion in a suitable manner ever improving our technical support MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD il CHAPTER 1 Introduction mikroC for 8051 HOW TO REGISTER The latest version of the mikroC for 8051 is always available for downloading from our website It is a fully functional software libraries examples and comprehensive 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 practi cal working applications with no thinking of demo limit If you intend to develop really complex projects in the mikroC for 8051 then you sho
358. ronment mikroC for 8051 Tools Toolbar Tools Toolbar comes with following default options Bespon 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 topics Keyboard shortcuts Integrated Tools Debugger Windows 26 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment PROJECT MENU OPTIONS Build Build All Projects ShiFt F9 Build Program Edit Search Paths Clean Project Folder Add File To Project Remove File Fram Project Mew Project Open Project Shift Ctri 0 Open Project Group 17 Close Project Group ki Save Project As Recent Projects 1 Close Project EL NEN M Build and program active project MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 21 CHAPTER 2 Environment mikroC for 8051 9 Open Project Group Project Group open Project Group Open project group EH Close Project Group Close project group Save active project file with the different Recent Projects Open recently used project Close Project Close active project Related topics Keyboard shortcuts Project Toolbar Creating New Project Project Manager Project Settings 28 MIKROELEKTRONIKA SOFTWARE AND HARDWAR
359. ronment mikroC for 8051 roid main wWoid PO 0 Pon Led Init LCD Out 1 1 txt 0 LCD Out 2 1 txt 1 delay 10001 Lcd Cmd 1 E DET qst LCD Outiz 23 txt z delay ms 500 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 a floating panel As you type the actual parameter the next expected parameter will become bold channel char 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 tem plate 44 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Autocomplete macros can retreive system and project information DATES current system date TIMES current system time 5 5 5 5 DEVICE device MCU name as specified in project settings DEVICE CLOCKS clock as specified in project settings COMPILERS c
360. ronments 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 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 mikroC for 805 you agree to the terms of this agreement Only one person may use licensed version of mikroC for 8051 compiler at a time Copyright mikroElektronika 2003 2008 This manual covers mikroC version 1 0 0 0 and the related topics Newer versions may contain changes without prior notice COMPILER BUG REPORTS The compiler has been carefully tested and debugged It 1s 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 mikroC for 8051 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 and or services marks are the property of the respec
361. s In order to hear the sound you need a piezo speaker or other hardware on designated port Also you must call Sound Init to prepare hardware for output before using this function Example Play sound of 1KHz in duration of 100ms sound Play 1000 100 Library Example The example is a simple demonstration of how to use the Sound Library for play ing tones on a piezo speaker 326 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Sound connections sbit Sound Play Pin at PO B3 74 End Sound connections void Tonel sound Play 500 200 Frequency 500Hz Duration 200ms 77 void 2 Gound Play Sso 2007 Frequency 555Hz Duration 200ms void Tone3 sound Play G25 2007 Frequency 625Hz Duration 200ms 77 void Melody 1 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 Tone1 Vie void ToneA Tones used in Melody2 function iso 42092 void 1 Sound 1 1450 20 void ToneE 4 sound Play l65D0 90912 void Melody2 Plays Melody2 unsigned short i tor Bs gt OF 4 ToneA ToneC ToneE pr void main PL 255 Configure PORTI as input
362. s must be unique within the scope in which they are defined Externally declared identifiers must be unique among externally declared variables Duplicate names are legal for different name spaces regardless of the scope rules For example MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 143 CHAPTER 5 Language Reference mikroC for 8051 int blue 73 open a block enum colors black red green blue violet white enumBrator blue 3 now hides outer declaration of int blue struct colors 4 int i 4 ILLEGAL colors duplicate tag double red 2 yf ILLEGAL redefinition of red blue 37 back in int blue scope DURATION Duration closely related to a storage class defines a period during which the declared identifiers have real physical objects allocated memory We also distin guish between compile time and run time objects Variables for instance unlike typedefs and types have real memory allocated during run time There are two kinds of duration static and local Static Duration Memory 15 allocated to objects with static duration as soon as execution 15 under way this storage allocation lasts until the program terminates Static duration objects usually reside in fixed data segments allocated according to the memory model in force All globals have static duration All functions wherever defined are objects with static duration Other variables can be given s
363. s an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit 108 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroC for 8051 Specifics Get_Fosc_kHz Prototype unsigned long Get Fosc kHz void Device clock in KHz rounded to the nearest integer Description Function returns device clock in KHz rounded to the nearest integer Note that Fosc kHz 1s library function rather than a built in routine it is presented in this topic for the sake of convenience CODE OPTIMIZATION Optimizer has been added to extend the compiler usability cut down the amount of code generated and speed up its execution The main features are Constant folding All expressions that can be evaluated in the compile time 1 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 the code MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 109 CHAPTER 3 Specifics mikroC for 8051 Value numbering The compiler recognizes if two expressio
364. s into one new token This is commonly used for constructing identifiers For example see the definition of macro spice for pasting two tokens into one identifier define SPLICE x y x y Now the call SPLICE cnt 2 will expand to the identifier 2 Note The mikroC for 8051 does not support the older nonportable method of token past ing using 1 r 216 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference CONDITIONAL COMPILATION Conditional compilation directives are typically used to make source programs easy to change and easy to compile in different execution environments The mikroC for 8051 supports conditional compilation by replacing the appropriate source code lines with a blank line All conditional compilation directives must be completed in the source or include file in which they have begun Directives Zelif Zelse and endif The conditional directives if elif else and endif work very similar to the common C conditional statements If the expression you write after has nonzero value the line group immediately following the 1 directive is retained in the translation unit The syntax 1s fit SONS LANL expression 1 lt s ction 1 gt constant expression 2 constant expression n lt Section gt else Lite section dendif Each if directive
365. s like this fields need to be unsigned struct tag unsigned bitfield declarator list Here tag is an optional name of the structure bit field declarator list is list of bit fields Each component identifer requires a colon and its width in bits to be explicitly specified Total width of all components cannot exceed two bytes 16 bits 168 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference As an object bit fields structure takes two bytes Individual fields are packed with in two bytes from right to left In bit field declarator list you can omit iden tifier s to create an artificial padding thus skipping irrelevant bits For example if there 15 a need to manipulate only bits 2 4 of a register as one block create a structure like this struct unsigned 2 Skip bits 0 and 1 no identifier here mybits 3 Relevant bits 2 3 and 4 Bits 5 6 and 7 are implicitly left out myreg Here is an example typedef struct io nibble 4 hi nibols 5 as high byte 8 myunsigned which declares the structured type myunsigned containing three components lo nibble bits 3 0 hi nibble bits 7 4 and high byte bits 15 8 Bit Fields Access Bit fields can be accessed in the same way as the structure members Use direct and indirect member selector and gt For example we could work with our previ ously declared myunsigned
366. signed short x pos unsigned short color Description Draws a vertical line on GLCD Parameters y start y coordinate of the line start Valid values 0 63 y end y coordinate of the line end Valid values 0 63 x pos X coordinate of vertical line Valid values 0 127 color color parameter Valid values 0 2 The parameter color determines the line color 0 white 1 black and 2 inverts each dot GLCD needs to be initialized see Gled Init routine Example Draw a vertical line between dots 10 5 and 20 25 Gilead y Lane gt 22 10 17 Glcd H Line Prototype void Glcd H Line unsigned short x start unsigned short x end unsigned short y pos unsigned short Nothing Description Draws a horizontal line on GLCD Parameters x start x coordinate of the line start Valid values 0 127 x end x coordinate of the line end Valid values 0 127 y pos y coordinate of horizontal line Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the line color 0 white 1 black and 2 inverts each dot Requires GLCD needs to be initialized see Glcd_Init routine Draw a horizontal line between dots 10 20 and 20 20 Gled H wate 105 j 250 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Glcd Rectangle Prototype void Glcd Rectangle unsigned short x upper left
367. single assembly instruction to code asm assembly instruction and asm assembly instruction Note semicolon and LF are terminating asm scope for single assembly instructions This 15 the reason why the following syntax 15 not asm block asm block of assembly instructions This code will be interpreted as single empty asm line followed compound statement MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 179 CHAPTER 5 Language Reference mikroC for 8051 The mikroC for 8051 comments both single line and multi line are allowed in embedded assembly code Accessing individual bytes is different as well For example a global variable var of type long i e 4 bytes can be accessed like this MOV 11 purs MOV 4 var4l JpuLs MOV vari2 puts MOV 4 var 3 4 puts ero If you want to know details about asm syntax supported by mikroC for 8051 it 1s recomended to study asm and ist files generated by compiler It is also recomend ed to check Include source lines in output files checkbox in Output settings INITIALIZATION in low byte of g var in high Dyte or g var in higher byte in highest byte 4 var wo The initial value of a declared object can be set at the time of declaration initializa tion A part of the declaration which specifies the initialization is called initializer Initializers for gl
368. sor macros The recursive nature of the declarator syntax allows complex declarators You ll probably want to use typedefs to improve legibility 1f constructing complex objects values Lvalue is an object locator an expression that designates an object An example of Ivalue expression is where P is any expression evaluating to a non null pointer A modifiable lvalue is an identifier or expression that relates to an object that can be accessed and legally changed in memory A const pointer to a constant for example is not a modifiable A pointer to a constant can be changed but its derefer enced value cannot MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 141 CHAPTER 5 Language Reference mikroC for 8051 Historically stood for left meaning that lvalue could legally stand on the left the receiving end of an assignment statement Now only modifiable lvalues can legally stand to the left of an assignment operator For example if a and b are non constant integer identifiers with properly allocated memory storage they are both modifiable Ivalues and assignments such as a 1 and b b are legal Rvalues expression a b is notlvalue a b a is illegal because the expression on the left is not related to an object Such expressions are sometimes called rvalues short for right values SCOPE AND VISIBILITY Scope The scope of an identifier 1s a part of the progr
369. sponds to the appropriate network traffic receive filter MAC Broadcast traffic receive fil ter flag When set MAC broadcast Spi Ethernet BROADCAST traffic will be disabled MAC Multicast traffic receive filter flag When set MAC multicast Spi Ethernet MULTICAST traffic will be disabled CRC check flag When set CRC cnn check will be disabled and packets Tp ET with invalid CRC field will be E E accepted ae MAC Unicast traffic receive filter 7 0x80 flag When set MAC unicast traffic Spi Ethernet UNICAST will be disabled MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 339 CHAPTER 6 Libraries Description Requires Example mikroC for 8051 Note Advance filtering available in the amp c28560 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 28760 module should be properly cofigured by the means ofSpi Ethernet Init routine Ethernet module has to be initialized See Spi Ethernet Init Ethernet Disable opi Bthernet CRC Spi Ethernet UNICAST disable checking and Unicast Spi Ethernet doPacket Prototype unsigned char Spi Ethernet doPacket Returns Description Requ
370. ssion2 Note if and else preprocessor statements directives look similar to if and else statements but have very different effects They control which source file lines are compiled and which are ignored MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 203 CHAPTER 5 Language Reference mikroC for 8051 204 SWITCH STATEMENT The switch statement is used to pass control to a specific program branch based on a certain condition The syntax of the switch statement is Switch expression Case Constant expression 1 Statement 1 Gase consLanLt expression n 7 statement nj default statement First the expression condition 15 evaluated The switch statement then compares it to all available constant expressions following the keyword case If a match 15 found switch passes control to that matching case causing the statement follow ing the match evaluates Note that constant expressions must evaluate to integer It 15 not possible to have two same constant expressions evaluating to the same value Parentheses around expression are mandatory Upon finding a match program flow continues normally the following instructions will be executed in natural order regardless of the possible case label If no case satisfies the condition the default case evaluates if the label default is speci fied For example if a variable i has value between 1 and 3 the following switch would alwa
371. st or volatile For more details refer to Storage Classes and Type Qualifiers For example Create 3 integer variables called x y and 7 and initialize x and y to the values 1 and 2 respectively int x 1 y 2 7 z remains uninitialized Create a floating point variable 9 with static modifier and initialize It to 0 25 static float 25 These are all defining declarations storage 1s allocated and any optional initializers are applied 174 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference LINKAGE An executable program is usually created by compiling several independent transla tion units then linking the resulting object files with preexisting libraries A term translation unit refers to a source code file together with any included files but with out the source lines omitted by conditional preprocessor directives A problem aris es when the same identifier is declared in different scopes for example in different files or declared more than once the same scope The linkage is a process that allows each instance of an identifier to be associated correctly with one particular object or function All identifiers have one of two link age attributes closely related to their scope external linkage or internal linkage These attributes are determined by the placement and format of your declarations together with an explicit or implic
372. string from to to The initial character of from overwrites the null char acter at the end of to The terminating null character is always appended to the result The function returns to 450 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries strncpy Prototype char strncpy char to char from int size Description Function copies not more than size characters from string from to to If copying takes place between objects that overlap the behavior is undefined If from is shorter than size characters then to will be padded out with null characters to make up the difference The function returns the resulting string to strspn Prototype int strspnichar char Description Function returns the length of the maximum initial segment of stri which consists entirely of characters from st r2 The termi nating null character at the end of the string is not compared Strncmp Prototype int strncmp char sl char s2 char len Description Function lexicographically compares not more than 1e characters characters that follow the null character are not compared from the string pointed by s to the string pointed by s2 The function returns a value indicating the s and s2 relationship Value Meaning lt s less than 52 51 equal to 52 sl greater than 52 Strstr Prototype char strstr char sl char 52 Descripti
373. structure is equal to the sum of its mem bers sizes It is often greater due to certain limitations of memory storage Structures and Functions A function can return a structure type or a pointer to a structure type mystruct funcl void funcl returns a structure mystruct func2 void 2 returns pointer to structure A structure can be passed as an argument to a function in the following ways void funclimvystruot 8 2 directly void func mystruct sptr via pointer 164 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference STRUCTURE MEMBER ACCESS Structure and union members are accessed using the following two selection opera tors period gt right arrow The operator is called the direct member selector and it is used to directly access one of the structure s members Suppose that the object s is of the struct type S and m is a member identifier of the type M declared in s then the expression s m yr direct access to member m is of the type M and represents the member object m in S The operator gt is called the indirect or pointer member selector Suppose that the object s is of the struct type s and ps 15 a pointer to s Then if m is a member iden tifier of the type M declared in s the expression ps m indirect access to member m identical to ps m is of the t
374. such that the will match after any line separator within the string and will match before any line separator Regular expressons works with line separators as recommended at www unicode org http www unicode org unicode reports tr18 Metacharacters Predefined classes w an alphanumeric character including w a nonalphanumeric d a numeric character D a non numeric s any space same as t n r f S space You may use w d and s within custom character classes Example routi de matches strings like routile routi6e and so on but not routine routime and so MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 71 CHAPTER 2 Environment mikroC for 8051 Metacharacters Word boundaries A word boundary is a spot between two characters that has a w on side of it and a ww on the other side of it in either order counting the imaginary characters off the beginning and end of the string as matching a wi b match a word boundary B match a non word boundary Metacharacters Iterators Any item of a regular expression may be followed by another type of metacharac ters iterators Using this metacharacters you can specify number of occurences of previous character metacharacter or subexpression Zero more greedy similar to 0 or more greedy similar to 1 zero or one greedy
375. t SPExpanderCS at 1 1 Inti initialize spi opi LEd Config 0 initialize lcd over spi interface Spi Lcd Out Prototype void Spi Lcd Out char row char column char text Description Prints text on the LCD starting from specified position Both string variables and literals can be passed as a text Parameters row Starting position row number column Starting position column number text text to be written Requires LCD needs to be initialized for SPI communication see Spi Led Config routines Example Write text Hello on LCD starting from row 1 columm 3j epi Led Curd 23 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 371 CHAPTER 6 Libraries mikroC for 8051 Spi Lcd Out Description Prints text on the LCD at current cursor position Both string vari ables 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 Led Config routines Example Write text Here at current cursor position Pet LEO GP NerEI LS Spi Lcd Chr Prototype void Spi Lcd Chr char Row char Column char Out Char Description Prints character on LCD at specified position Both variables and literals can be passed as character Parameters Row Writing position row number Column Writing position column number Out Char character to be written
376. t The line ifdef identifier has exactly the same effect as if 1 If identifier is currently defined and the same effect as if 0 if identifier 1s currently undefined The other directive ifndef tests true for the not defined condition producing the opposite results The syntax thereafter follows that of if elif else and endif An identifier defined as NULL 15 considered to be defined 218 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER mikroC for 8051 Libraries mikroC for 8051 provides a set of libraries which simplify the initialization and use of 8051 compliant MCUs and their modules 219 CHAPTER 6 Libraries mikroC for 8051 MIKROC FOR 8051 LIBRARIES mikroC for 8051 provides a set of libraries which simplify the initialization and use of 8051 compliant MCUs and their modules Use Library manager to include mikroC for 8051 Libraries you project Hardware 8051 specific Libraries CANSPI Library EEPROM Library Graphic LCD Library Keypad Library LCD Library Manchester Code Library OneWire Library Port Expander Library PS 2 Library RS 485 Library Software I2C Library 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 Standard ANSI C Librar
377. t such as a variable to an integral object results in automatic sign extension Objects of type signed char always use sign extension objects of type unsigned char always has its high byte set to zero when converted to int Converting a longer integral type to a shorter type truncates the higher order bits and leaves low order bits unchanged Converting a shorter integral type to a longer type either sign extends or zero fills the extra bits of the new value depending on whether the shorter type is signed or unsigned respectively Note Conversion of floating point data into integral value in assignments or via explicit typecast produces correct results only if the float value does not exceed the scope of destination integral type In details Here are the steps the mikroC for 8051 uses to convert the operands in an arithmetic expression First any small integral types are converted according to the following rules char converts to int Signed char converts to int with the same value short converts to int with the same value sign extended unsigned short converts to unsigned int with the same value zero filled 5 enum converts to int with the same value ju N After this any two values associated with an operator are either int including the long and unsigned modifiers or float equivalent with double and long double in the mikroC for 8051 1 If either operand is float the other operand 15 converted
378. t get routines The user puts data in the transmit buffer by using some of the Spi Ethernet put routines The func tion must return the length in bytes of the UDP reply or 0 if noth ing to transmit If you don t need to reply to the UDP requests just define this function with a return 0 as single statement Parameters remoteHost client s IP address remotePort client s port destPort port to which the request 15 sent reqLength 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 Ethernet module has to be initialized See Spi Ethernet Init Example This function is internally called by the library and should not be called by the user s code Library Example This code shows how to use the 8051 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 upper char with a header made of remote host 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 0 t7 will toggle P3 b0 to P3 b7 bit and return HTML main page all other requests return also HTML main page 346 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries
379. ta Description Writes command to T6963C controller via SPI interface Parameters Ddata command to be written Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example opi T69620 WriteComma nd opi T69620 CURSOR POINTER SET MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 387 CHAPTER 6 Libraries mikroC for 8051 Spi T6963C SetPtr Prototype void Spi T6963C SetPtr unsigned int p unsigned char Description Sets the memory pointer p for command c Parameters address where command should be written c command to be written Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Spi T6963C WriteCommand Spi T6963C CURSOR POINTER SET Spi T6963C WaitReady Prototype void Spi T6963C WaitReady void e the status byte and loops until Toshiba GLCD module is ready Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Spi 696 WaitReadyl Spi T6963C Fill Prototype void Spi T6963C Fill unsigned char v unsigned int start unsigned int len Description Fills controller memory block with given byte Parameters v byte to be written start Starting address of the memory block 1en length of the memory block in bytes Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine 388 MIKROELEKTRONIKA SOFTWARE AND HAR
380. tants define flags related to the CANSPI module configuration The functions CANSPIInitialize CANSPISetBaudRate CANSPISetMask and CANSPISetFilter expect one of these or a bitwise combina tion as their argument constr ghar CANSPI CONFIG DEFAULT OxFF p CANSPI CONFIG PHSEG2 PRG 0x01 CANSPI CONFIG PHSEG2 PRG ON OxFF XXXXXXX1 CANSPI CONFIG PHSEG2 PRG OFF OxFE XXXXXXX0 CANSPI CONFIG LINE FILTER BIT 0x02 CANSPI CONFIG LINE FILTER ON OxFF XXXXXX1X CANSPI CONFIG LINE FILTER OFF OxFD XXXXXXOX CANSPI CONFIG SAMPLE BIT 0x04 CANSPI CONFIG SAMPLE ONCE OxFF XXXXX1XX CANSPI CONFIG SAMPLE THRICE OxFB XXXXXOXX CANSPI CONFIG MSG TYPE BIT 0x08 CANSPI CONFIG STD MSG OxFF XXXX1XXX CANSPI CONFIG XTD MSG OxF7 XXXXOXXX CANSPI CONFIG DBL BUFFER BIT 0 10 CANSPI CONFIG DBL BUFFER ON OxFF XXX1XXXX CANSPI CONFIG DBL BUFFER OFF OxEF XXXOXXXX CANSPI CONFIG MSG BITS 0x60 CANSPI CONFIG ALL MSG OxFF 11 CANSPI CONFIG VALID XTD MSG OxDF X10XXXXX CANSPI CONFIG VALID STD MSG OxBF 1 CANSPI CONFIG ALL VALID MSG Ox9F X00XXXXX You may use bitwise AND s to form config byte out of these values For exam ple init CANSPI CONFIG SAMPLE THRICE amp CANSPI CONFIG PHSEG2 PRG ON amp CANSPI CONFIG STD MSG amp CANSPI CONFIG DBL BUFFER ON amp CANSPI CONFIG VALID XTD MSG amp CANSPI CONFIG LINE FILTER OFF CANSPII
381. tatic duration by using the explicit static or extern storage class specifiers In the mikroC for 8051 static duration objects are not initialized to zero or null in the absence of any explicit initializer Don t mix static duration with file or global scope An object can have static dura tion and local scope see the example below Local Duration Local duration objects are also known as automatic objects They are created on the stack or in a register when an enclosing block or a function is entered They are deallocated when the program exits that block or function Local duration objects must be explicitly initialized otherwise their contents are unpredictable 144 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference The storage class specifier auto can be used when declaring local duration variables but it 1s usually redundant because auto is default for variables declared within a block An object with local duration also has local scope because it does not exist outside of its enclosing block On the other hand a local scope object can have static dura tion For example void f local duration variable init a upon every call to f int a 1 Static duration variabile init b oniy upon first call to static int b 1 checkpoint ar void main At checkpoint we will have fils bel
382. te charac ter decimal 0 31 and 127 otherwise returns zero isdigit nw Description Function returns 1 if the character 1s a digit 0 9 otherwise returns zero isgraph Description Function returns 1 if the character 1s a printable excluding the space decimal 32 otherwise returns zero islower Description Function returns if the character 1s a lowercase letter a z otherwise returns zero ispunct Prototype unsigned short ispunct char character Description Function returns 1 if the character 15 a punctuation decimal 32 47 58 63 91 96 123 126 otherwise returns zero Prototype unsigned short isspace char character Description Function returns 1 if the character 15 a white space space tab CR HT VT NL FF otherwise returns zero MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 437 CHAPTER 6 Libraries mikroC for 8051 isupper Prototype unsigned short isupper char character Description Function returns 1 if the character is an uppercase letter A Z otherwise returns zero isxdigit Description Function returns if the character is a hex digit 0 9 A F a f otherwise returns zero toupper Prototype unsigned short toupper char character Description If the character is a lowercase letter a z the function returns an uppercase letter Otherwise the function returns an unchanged input parameter tolower
383. ter Library Example The code demonstrates how to use SPI library functions for communication between SPI module of the MCU and MAX7219 chip MAX7219 controls eight 7 segment displays MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 331 CHAPTER 6 Libraries mikroC for 8051 Serial 7 seg Display connections sbit CHIP SEL PliB0 Chip Select pin definition End Serial 7 seg Display connections void Select max Function for selecting MAX7219 CHIP SEL 0 Delay void Deselect max Function for deselecting MAX7219 Delay us 1 CHIP SEL 1 void Max7219 init Initializing MAX7219 select maxi Spi Write 0x09 BCD mode for digit decoding Deselect select max Spi Write Spi Write 0x0F Segment luminosity intensity Deselect maxi select maxi Spi Write 0x0B Spi Write 0x07 Display refresh Deselect maxi select max Spi Write UxUC 7 Spi Write 0x01 44 Turn the display Deselect maxi Select max Spi Write 0x00 Spi Write OxFF 77 No test Deselect maxi char digit position digit value void main ISILU Initialize SPI module standard configuration 7 Instesd of init you can use SPI init Advanced as shown below Spi Init Advanced MASTER OSC DIV4 DATA ORDER MSB CLK IDLE LOW IDLE 2 ACTIVE 332 MIKROELEKTRONIKA SOFTWAR
384. ter Valid values 0 disable cursor blinking and 1 enable cursor blinking Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Example enable cursor blinking T5963 Cursor Blink l Library Example The following drawing demo tests advanced routines of the T6963C GLCD library Hardware configurations in this example are made for the T6963C 240x128 display Easy8051B board and 8958253 426 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 Finclude TOI6IC modu unsigned char Pointer to unsigned char Pointer to sbit 1T6963C_ sbit 1T6963C_ sbit 1T6963C_ sbit 6963 End T6963C yh DIOC a const code char const code char einstein void main char idata t char idata t cha int cha int unsigned unsigned unsigned unsigned P1 PU d ik Us data bus DIL 2 bit Dit brt 18 i8 is is hk Xe BR Xe BH 03 0 x 7 initialize T6963C init 240 ge CHAPTER 6 Libraries le connections sfr at PO DATA BUS port sfr Polos prFEIPorLt at LCONTRUL ctrlwr at P1 B2 WR write signal ctrird at RD read signal ctrlcd at 1 0 CD command data signal ctrirst at Pl B4 RST reset signal module connections ures stored in ROM EINSTEIN WOU
385. ter Receive RS485master Send RS485slave Init RS485slave Receive RS485slave Send RS485master Init Initializes MCU as a Master for RS 485 communication Requires rs485 transceive Variable must be defined before using this function This pin is connected to RE DE input of RS 485 trans ME 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 UART HW module needs to be initialized See Uart Init rs485 module pinout sbit rs485 rtranscelye P3 B527 transmit receive control set to port3 bit2 Uart Initi 9600 3 13natialirze usart module Rs485master Init intialize mcu as a Master for RS 485 communication 302 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries RS485master_Receive Prototype void Rs485master Receive char data buffer Description Receives messages from Slaves Messages are multi byte so this routine must be called for each byte received Parameters data buffer 7 byte buffer for storing received data the fol lowing manner data 0 2 message content number of message bytes received 1 3 15 set to 255 when message 15 received 1s set to 255 if error has occurred address of the Slave which sent the message The function automatically adjusts data 4 and data 5 upon every received message These fl
386. ter missing for example 82 Invalid parameter string Specifier needed s not found 551 Index out of bounds Array dimension must be greater then 0 Const expression expected Integer const expected Recusion in definition Array corupted Arguments cannot be of void type Arguments cannot have explicit memory specificator Bad storage class Pointer to function required Function required Pointer required Illegal pointer conversion to double Integer type needed Members can not have memory specifier Members can not be of bit or sbit type Too many initializers Too many initializers of subaggregate Already used 551 Illegal expression with void MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 97 CHAPTER 2 Environment mikroC for 8051 Address must be greater than 0 551 Identifier redefined User abort Expression must be greater then 0 Invalid declarator expected or identifier Typdef name redefined 551 Declarator error Specifer qualifier list expected s already used ILevel can be used only with interrupt service routines 5 expected but gt s found Expected 551 Identifier redefined expected but gt s found expected but gt s found case out of switch expected but gt s found label out of switch Switch ex
387. th either lt header_ name gt or header name formats exists PREPROCESSOR OPERATORS The pound sign is a preprocessor directive when it occurs as the first non white space character on a line Also and 4 perform operator replacement and merging during the preprocessor scanning phase Operator In C preprocessor a character sequence enclosed by quotes is considered a token and its content is not analyzed This means that macro names within quotes are not expanded MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 215 CHAPTER 5 Language Reference mikroC for 8051 If you need an actual argument the exact sequence of characters within quotes as a result of preprocessing use the operator in macro body It can be placed in front of a formal macro argument in definition in order to convert the actual argument to a string after replacement For example let s have macro LCD PRINT for printing variable name and value on LCD define LCD PRINT val Lcd Custom Out Cp val N Lou Custom Dunt CpiintToSLri ival Now the following code LCD PRINT temp will be preprocessed to this Lcd Custom Out Cp temp Lcd Custom Out Cp IntToStr temp Operator Operator is used for token pasting Two tokens be pasted merged together by placing in between them plus optional whitespace on either side The pre processor removes whitespace and combining the separate token
388. the main window by default The Error Window 15 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 Warnings v Hints Line Message No Message Text Unit 0 1 mikroc8051 exe MSF DEG 8958253 5 C 011111114 010 0 125 All files Preprocessed in 31 ms 0 121 Compilation Started LedBlinking c 21 300 Syntax Error expected found LedBlinking c 21 399 expected but P2 found LedBlinking c 22 421 7 expected found LedBlinking c 31 421 Y expected found LedBlinking c 0 102 Finished with errors 06 Mar 2008 09 26 59 LedSlinking meproj Double click the message line in the Error Window to highlight the line where the error was encountered Related topics Error Messages STATISTICS After successful compilation you can review statistics of your code Click the Statistics Icon Memory Usage Windows Provides overview of RAM and ROM usage in the form of histogram RAM Memory 52 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Data Memory Displays Data memory usage in form of histogram Statistics B Memory Usage RAM Memory Usage locations 68 of 96 33 Free data RAM 63 Used data RAM ROM Allocation 3455 Sb E Proced
389. tion Calls 103 Fil PET 104 20 nae 104 MONES coh de ea ee woe 3 oma 105 22355 ee ee Bull war 105 Delay INS ae Lm 106 Dolay US ADT 106 Delay CYC 107 VOGIAY T 107 GIOCK MIZ 32522 See ae eee eee Babee eee EE d ES 108 CIOCK och cect 108 Code Optimization 109 Constant 109 Constant propagation 109 propagation 109 Sel FOSO KA wae seme 109 Value numbering 110 Dead code ellimination 110 Stack allocation 110 Local vars optimization 110 Better code generation and local optimization 110 CHAPTER 4 0091 SPCCHICS peed uetus 112 Types ened oia e 112 Nested Calls Limitations 112 9051 Memory Organization 113 vili MIKROELEKTRONIKA SOFTWAR
390. tion returns greater of the two integers a and b Function returns lower of the two integers a and b 446 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries rand Prototype rand Description Function returns a sequence of pseudo random numbers between 0 and 32767 The function will always produce the same sequence of numbers unless srand is called to seed the start point srand Prototype void srand unsigned x Description Function uses as a starting point for a new sequence of pseudo random numbers to be returned by subsequent calls to rand No values are returned by this function xtoi Prototype unsigned xtoi register char s Description Function converts the input string s consisting of hexadecimal digits into an integer value The input parameter s should consist exclusively of hexadecimal digits with an optional whitespace and a sign at the beginning The string will be processed one char acter at a time until the function reaches a character which it doesn t recognize including a null character Div Structures typedef struct divstruct int quot int rem P Hx t typedef struct ldivstruct long quot long rem p Ty typedef struct uldivstruct unsigned long quot unsigned long rem I uldir t MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 447 CHAPTER 6 Libraries mi
391. tive owners 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Table of Contents CHAPTER 1 CHAPTER 2 CHAPTER 3 CHAPTER 4 CHAPTER 5 CHAPTER 6 Introduction to mikroC 8051 mikroC for 8051 Environment mikroC for 8051 Specifics 8051 Specifics mikroC for 8051 Language Reference mikroC for 8051 Libraries Table of Contents mikroC for 8051 CHAPTER 1 oe es Pee 2 Where to 9 mikroElektronika Associates License Statement and Limited Warranty 4 IMPORTANT READ CAREFULLY 4 LIMITED 5 HIGH RISK ACTIVITIES 6 GENERAL PROVISIONS de ebb 6 Technical sos sawat ene Pee xeu eR oe a thd oe 7 How to 8 Who Gets the License Key 8 How to Get License Key 8 CHAPTER 2 eae etek eee amp bee ce gets ee a TEE 12 Main Menu OptionS 13 File Menu Options 14 Edit Menu OptionS 15
392. to be executed 15 color highlighted blue by default Note The Software Simulator simulates the program flow and execution of instruc tion lines but it cannot fully emulate 8051 device behavior 1 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 C code Just select desired variable reg ister from Select variable from list drop down menu and click the Add Button oo i by 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 90 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC for 8051 Environment Variables can also be removed from the Watch window just select the variable that you want to remove and then click the Remove Button Add All Button m AddAl adds all variables Remove All Button removes all variables Remove All You can also expand coll
393. to fill graphic panel with Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example clear current graphic panel Spi T6963C GrFill 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 399 CHAPTER 6 Libraries mikroC for 8051 Spi T6963C TxtFill Prototype void Spi T6963C TxtFill unsigned char v Description Fill current text panel with appropriate value 0 to clear Parameters v this value increased by 32 will be used to fill text panel Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example clear current text panel TOCCO TEXCESAI110 Spi T6963C Cursor Height Prototype void Spi T6963C Cursor Height unsigned char n Description Set cursor size Parameters n cursor height Valid values 0 7 Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine 400 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi T6963C Graphics Prototype void Spi T6963C Graphics char n Description Enable disable graphic displaying Parameters n graphic enable disable parameter Valid values 0 disable graphic dispaying and 1 enable graphic displaying Requires Toshiba GLCD module needs to be initialized See Spi T6963C Config routine Example enable graphic displaying opi 7092632 Graphics 1
394. to force arguments to change their type to a proper one Consider the following code int limit 32 char ch A long res prototype extern long func long parl long par2 marini 4 funciliumit 77 function call SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 185 CHAPTER 5 Language Reference mikroC for 8051 Since the program has the function prototype for func it converts limit and ch to long using the standard rules of assignment before it places them on the stack for the call to func Without the function prototype 1imit and ch would be placed on the stack as integer and a character respectively in that case the stack passed to func will not match size or content that func expects which can cause problems ELLIPSIS OPERATOR The ellipsis consists of three successive periods with no whitespace interven ing An ellipsis can be used in the formal argument lists of function prototypes to indicate a variable number of arguments or arguments with varying types For example func 190 n Char This declaration indicates that func will be defined such a way that calls must have at least two arguments int and char but can also have any number of addition al arguments Example include lt stdarg h gt int addvararg char al va Lipt ap char temp va srartiap al while temp va arg
395. tom right y coordinate of the lower right box corner Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the color of the box fill 0 white 1 black and 2 inverts each dot GLCD needs to be initialized see Glcd_ Init routine Example box between dots 5 15 and 20 40 Gled Boxi 1595 sU 20 17 Glcd Circle Prototype v id Circle int x center Aint y center int radius unsigned short color Description Draws a circle on GLCD Parameters x center X coordinate of the circle center Valid values 0 127 y center y coordinate of the circle center Valid values 0 63 radius radius size color color parameter Valid values 0 2 The parameter color determines the color of the circle line 0 white 1 black and 2 inverts each dot GLCD needs to be initialized see Gled Init routine Example Draw a circle with center in 50 50 and radius 10 Gled 20 L0 IM 252 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Glcd Set Font Prototype void Glcd Set Font const char activeFont unsigned short aFontWidth unsigned short aFontHeight unsigned int aFontOffs Returns Nothing Description Sets font that will be used with Gled Write Char and Gled Write Text routines Parameters activeFont font to be set Needs to be formatted as an array of char aFont
396. tructure member selectors and gt be careful when doing this MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 167 CHAPTER 5 Language Reference mikroC for 8051 Referring to declarations from the example above pm amp mu mu d 4 016 tmp mu d OK mu d 4 016 tmp mu i peculiar result pm gt i 3 tmp mu i OK mu i 3 The third line is legal since mu i is an integral type However the bit pattern in mu i corresponds to parts of the previously assigned double As such it probably won t provide an useful integer interpretation When properly converted a pointer to a union points to each of its members and vice versa BIT FIELDS Bit fields are specified numbers of bits that may or may not have an associated iden tifier Bit fields offer a way of subdividing structures into named parts of user defined sizes Structures and unions can contain bit fields that can be up to 16 bits You cannot take the address of a bit field Note If you need to handle specific bits of 8 bit variables char and unsigned short or registers you don t need to declare bit fields Much more elegant solution is to use the mikroC for 8051 s intrinsic ability for individual bit access see Accessing Individual Bits for more information Bit Fields Declaration Bit fields can be declared only structures and unions Declare a structure normal ly and assign individual field
397. turns 1 otherwise it returns 0 All relational operators associate from left to right Relational Operators Overview Precedence of arithmetic and relational operators is designated in such a way to allow complex expressions without parentheses to have expected meaning 4 5 1 0 7 gt 5 gt c 1 0 Do not forget that relational operators return either 0 or 1 Consider the following examples B gt 7 returns 0 lt 20 2 this be tricky Bem 13 gt 8 returns U B 13 gt D gt 8 1 5 7 18 gt BD X 3 perurns 1 as gt 3 I1 3 gt 1 bh X35 returns 1 fa b 5 gt 4 ax lt 5 gt 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 191 CHAPTER 5 Language Reference mikroC for 8051 BITWISE OPERATORS Use the bitwise operators to modify individual bits of numerical operands Bitwise operators associate from left to right The only exception is the bitwise com plement operator which associates from right to left Bitwise Operators Overview bitwise AND compares pairs of bits and returns 1 1f both bits are 1 otherwise returns 0 bitwise inclusive OR compares pairs of bits and returns 1 1f either or both bits are 1 other wise returns 0 bitwise exclusive OR XOR compares pairs of bits and retu
398. uld consider the possi bility of purchasing the license key Who Gets the License Key Buyers of the mikroC for 8051 are entitled to the license key After you have com pleted the payment procedure you have an option of registering your mikroC 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 5 Fill out the registration form figure below select your distributor and click the Send button 9 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroC for 8051 Introduction How Register Step 1 Fill in the form below Please make sure you fill in all required fields Step 2 Make sure that you provided a valid email address in the EMAIL edit box This email will be used for sending you the activation key Step 3 Make sure you select a correct distributor which will make the registration process faster If your distributor 15 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 4 default email client will open with ready to send message Note If ernail 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
399. umber of elements is n elements of array can be approached as variables array name 0 name n l1 orf Here are a few examples of array declaration define MAX 50 int vector L0 declares an array of 10 integers float vector two declares an array of 50 floats float vector three MAX 20 4 declares an array Array Initialization An array can be initialized in declaration by assigning it a comma delimited sequence of values within braces When initializing an array in declaration you can omit the number of elements it will be automatically determined according to the number of elements assigned For example Declare an array which holds number of days in each month int 12 amp 1231 28 21 20 31 230 321 31 320 21 30 231 4 152 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference This declaration is identical to the previous one int days 121 20 21 20 31 20 31 21 30 21 320 217 If you specify both the length and starting values the number of starting values must not exceed the specified length The opposite is possible in this case the trailing excess elements will be assigned to some encountered runtime values from mem ory In case of array of char you can use a shorter string literal notation For example The two declarations are identical const char msgl
400. ures Spe Locations Used data RAM XData Memory Displays XData memory usage in form of histogram Statistics Memory Usage RAM Memory Usage locations 0 Used Xdata RAM iData bD ata Pdata SFR GPR ROM ROM Allocation Procedures Size Locations Free Xdata RAM MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 53 CHAPTER 2 Environment mikroC for 8051 iData Memory Displays iData memory usage in form of histogram Statistics Memory Usage RAM Memory Usage locations Data 10026 of 128 128 Free Idata RAM data 0 Used Idata bD ata Pdata SFR GPR ROM Allocation Procedures Size Locations 055 01 128 Free Used Idata bData Memory Displays bData memory usage in form of histogram Statistics Memory Usage RAM Memory Usage locations Sum 100 of 16 iData Pdata SFR GPR ROM ROM Allocation Procedures Size Locations Free Bdata RAM Used 54 SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC for 8051 PData Memory CHAPTER 2 Environment Displays PData memory usage in form of histogram Statistics E Memory Usage Data ROM ROM Allocation E Procedures Size Locations RAM Memory Usage locations 100 of 75 75 Free Pdata RAM ee
401. urrent compiler version These macros can be used in template code see template ptemplate provided with mikroC for 8051 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 Sf 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 simple click of a mouse using the Comment Icon 1 and Uncomment Icon 1 7 from the Code Toolbar Bookmarks Bookmarks make navigation through a large code easier To set a bookmark use Ctrl Shift number To jump to a bookmark use Ctrl number Goto Line The Goto Line option makes navigation through a large code easier Use the short cut Ctrl G to activate this option MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 45 CHAPTER 2 Environment mikroC for 8051 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 Lu Functions Globals TypeDef Tags Includes Following options are available in the Code Explorer Expand Collapse all nodes tr
402. vely specify long versions of the integer types u o x and x You must ensure that the argument type matches that of the for mat specification You can use type casts to ensure that the proper type 15 passed to sprintf 464 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries sprintl Prototype Sprintl char wh const char f Returns function returns the number of characters actually written to destination string The same as sprintf except it doesn t support float type numbers sprinti Prototype Sprinti char wh const char f Returns function returns the number of characters actually written to destination string Description The same as sprintf except it doesn t support long integers and float type numbers Library Example This 1s a demonstration of the standard C library sprintf routine usage Three differ ent representations of the same floating poing number obtained by using the sprintf routine are sent via UART double ww 1 2587538 1 char buffer 15 Function for sending string to UART void UartWriteText char txt while txt Jart 77 Function for sending const string to void UartWriteConstText const char txt while txt Uart void main Vart Init 4800 Initialize UART module at 4800 bps Delay ms 10 UartWriteConstText Floating p
403. ween the mikroC character set and regular ASCII set eg if A is 65 in ASCII character and A is 45 in the mikroC character set aFontOffs 1s 20 Demo fonts supplied with the library have an offset of 32 which means that they start with space The user use fonts given in the Lib GLCD fonts c 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 Gled Bet Ponti imvyiont 2 4 227 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries Spi Glcd Write Char Prototype void SPI Glcd Write Char char chrl char x pos char page num char color Returns Nothing Description Prints character on GLCD Parameters chr1 character to be written x pos character starting position on x axis Valid values 0 127 FontWidth page num the number of the page on which character will be written Valid values 0 7 color color parameter Valid values 0 2 The parameter color determines the color of the character 0 white 1 black and 2 inverts each dot Note For x axis and page layout explanation see schematic at the bottom of this page Requires GLCD needs to be initialized for SPI communication see Spi Gled Init routines Use the Spi Gled Set Font to specify the font for display
404. werful feature rich development tool 8051 microcon trollers It is designed to provide the programmer with the easiest possible solution to developing applications for embedded systems without compromising perform ance or control mikroC for 8051 CHAPTER 1 Introduction B p os LA E m E nig P n d P SEER T m 775 7 qot 0 HERE gum z ne 1 1 mikroC IDE Features mikroC for 8051 allows you to quickly develop and deploy complex applications Write your C source code using the built in Code Editor Code and Parameter Assistants Code Folding Syntax Highlighting Auto Correct Code Templates and more Use included mikroC 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 2 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroC for 8051 Introduction Inspect program flow and debug executable logic with the integrated Software Simulator Get detailed reports and graphs RAM and ROM map code statistics assembly listing calling tree and more mikroC 8051 provides plenty of examples to expand develop and use as
405. with blanks Parameters input byte to be converted output destination string Destination string should be at least 4 characters in length Example unsigned short t char txt 4 txt ff txt is 24 blank here MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 455 CHAPTER 6 Libraries mikroC for 8051 ShortToStr Prototype void ShortToStr short input char output Description Converts input signed short number to a string The output string has fixed width of 5 characters including null character at the end string termination The output string is right justified and remaining positions on the left if any are filled with blanks Parameters input signed short number to be converted output destination string Destination string should be at least 5 characters in length Example short t char a ShortUoStrit 77 tet zs fone plank here WordToStr Prototype void WordToStr unsigned input char output Description Converts input word to a string The output string has fixed width of 6 characters including null character at the end string termina tion The output string 15 right justified and the remaining posi tions on the left 1f any are filled with blanks Parameters input WOrd to be converted output destination string Destination string should be at least 5 characters in length Exam
406. with the const qualifier all objects need to be initialized The mikroC for 8051 treats objects declared with the const qualifier the same as erals or preprocessor constants If the user tries to change an object declared with the const qualifier compiler will report an error MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 177 CHAPTER 5 Language Reference mikroC for 8051 For example const double PI 3 14159 Qualifier volatile The qualifier volatile implies that a variable may change its value during runtime independently from the program Use the volatile modifier to indicate that a variable can be changed by a background routine an interrupt routine or I O port Declaring an object to be volatile warns the compiler not to make assumptions concerning the value of an object while evaluating expressions in which it occurs because the value could be changed at any moment TYPEDEF SPECIFIER The specifier typedef introduces a synonym for a specified type The typedef dec larations are used to construct shorter or more convenient names for types already defined by the language or declared by the user The specifier typedef stands first in the declaration typedef type definition synonym The typedef keyword assigns synonym to type definition The synonym needs to be a valid identifier A declaration starting with the typedef specifier does not introduce an object or a function of a given type but
407. writ ten wrdata data to be written Note Specified memory location will be erased before writing Starts Example unsigned short eeWrite 0x55 unsigned int wrAddr 0x732 Eeprom WriteiwrAddr eeWrite Eeprom Write Block Prototype unsigned short Eeprom Write Block unsigned int address unsigned short ptrdata Returns 0 writing was eed 1 If error occured Description Writes one EEPROM row 32 bytes block of data Parameters address starting address of the EEPROM memory block to be written ptrdata data block to be written Note Specified memory block will be erased before writing starts Requires EEPROM module must support block write operations It is the user s responsibility to maintain proper address alignment In this case address has to be a multiply of 32 which is the size in bytes of one row of MCU s EEPROM memory Example unsigned int wrAddr 0 0100 unsigned short iArr 32 m d LAM DR ET a EU 0 Eeprom Write Block wrAddr iArr MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 241 CHAPTER 6 Libraries mikroC for 8051 Library Example This example demonstrates using the EEPROM Library with 78958253 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 PO P1 and P2 Char dat 321 412 Data buffer loop variable void main 31 dat
408. x33 Variable i will occupy 1 byte at address 0x33 long 1111 absolute 0x30 77 Variable will ocoupbpy 4 bytes at xJU U xSI UxSZ 0X337 thus changing i changes jjjj highest byte at the same time and vice versa Directive org Directive org specifies a starting address of a routine in ROM Directive org is appended to the function definition Directives applied to non defin ing declarations will be ignored with an appropriate warning issued by the linker Here is a simple example void func int par org 0 200 7 7 Punction will start address 0x200 nop Note See also funcall pragma 102 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroC for 8051 Specifics INDIRECT FUNCTION CALLS If the linker encounters an indirect function call by a pointer to function it assumes that any of the functions addresses of which were taken anywhere in the program can be called at that point Use the pragma unca11 directive to instruct the linker which functions can be called indirectly from the current function 1 rune called iunc called runc A corresponding pragma must be placed in the source module where the function func name 15 Implemented This module must also include declarations of all func tions listed in the called func list These functions will be linked if the function func name is called in the code no matter whethe
409. xample mikroC for 8051 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 CAN SPI Extra Board or similar hardware See connection example at the bottom of this page send message extended CAN message with the appro priate ID and data char tx Tlags char datal 8 long msg id CANSPISetOperationMode MODE NORMAL OxFF set NORMAL mode CANSPI must be in mode in which transmission is possible tx flags CANSPI TX PRIORITY 0 amp CANSPI TX XTD FRAME set message flags CANSEPINTICE meg 10 2 tx 18645 CANSPI Constants There is a number of constants predefined in the CANSPI library You need to be familiar with them in order to be able to use the library effectively Check the example at the end of the chapter CANSPI OP MODE The CANSPI OP MODE constants define CANSPI operation mode Function CANSPISetOperationMode expects one of these as it s argument const char CANSPI MODE BITS CANSPI MODE NORMAL CANSPI MODE SLEEP CANSPI MODE LOOP CANSPI MODE LISTEN CANSPI MODE CONFIG OxEO Use this to access opmode bits 0x00 0x20 0 40 0 60 Dx 232 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC for 8051 Libraries CANSPI CONFIG FLAGS The CANSPI CONFIG FLAGS cons
410. ype and represents the member object m in s The expression ps gt m is a convenient shorthand for m For example struct mystruct int i char str 21 double d 8 amp 5 s i 3 assign to the i member of mystruct s sptr gt gd e 1 23 assign to the d member of mystruct s The expression s is lvalue providing that s is lvalue and m 15 not an array type The expression spt r gt m 15 an lvalue unless m is an array type MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 165 CHAPTER 5 Language Reference mikroC for 8051 Accessing Nested Structures If the structure B contains a field whose type is the structure A the members of A can be accessed by two applications of the member selectors struct A int j double x Po struct B int i struct A aa double uS Bid 2 assign 3 to the i member of B s aa j 2 assign 2 to the j member of A Sotr d 1 23 assign 1 23 to the d member of B sptr gt aa x 3 14 assign 3 14 to x member of A Structure Uniqueness Each structure declaration introduces a unique structure type so that in struct A int i j double d aa aaa struct B int i j double d bb the objects aa and aaa are both of the type struct A but the objects aa and bb are of different structure types Structures can be assigned only if the source and destina tion have the same type aa a
411. ype void T6963C SetPtr unsigned int p unsigned char c Description Sets the memory pointer p for command c Parameters p address where command should be written c command to be written Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine Example TOSPSL GOLPLIITBSOSL grBbomeAddr Start T6963C ADDRESS POINTER SET T6963C WaitReady Description Pools the status byte and loops until Toshiba GLCD module is ready Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine T6963C Fill Prototype void 6963 Fill unsigned char v unsigned int start unsigned int len Description Fills controller memory block with given byte Parameters v byte to be written start Starting address of the memory block jen length of the memory block in bytes Requires Toshiba GLCD module needs to be initialized See the T6963C Init routine T6963C Fill 0x33 0x00FF 0x000F MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 413 CHAPTER 6 Libraries mikroC for 8051 T6963C_Dot Prototype void 6963 Dot int x int y unsigned char color Description Draws a dot in the current graphic panel of GLCD at coordinates x y Parameters x dot position on x axis y dot position on y axis color color parameter Valid values T6963C BLACK and T6963C WHITE Requires Toshiba GLCD module needs to be initialized
412. ys return it as 4 switch i case 1 i case 2 itt case 3 itt To avoid evaluating any other cases and relinquish control from switch each case should be terminated with break Here is a simple example with switch Suppose we have a variable phase with only 3 different states 0 1 or 2 and a corresponding function event for each of these states This is how we could switch the code to the appopriate routine MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC for 8051 Language Reference Switch phase case 0 Lo break case 1 Mid break case 2 Hi break default Message Invalid state Nested switch Conditional switch statements can be nested labels case and default are then assigned to the innermost enclosing switch statement ITERATION STATEMENTS LOOPS Iteration statements allows to loop a set of statements There are three forms of iter ation statements in the mikroC for 8051 while do for WHILE STATEMENT The while keyword is used to conditionally iterate a statement The syntax of the while statement is while expression statement The statement executes repeatedly until the value of expression 1s false The test takes place before statement 15 executed Thus if expression evaluates to false on the first pass the loop does not execute Note that parentheses around expression are mandatory Here is an example of ca
413. ystruct MUStruct DS Arrol 111 j as struct s y Hrrhourt cag typedef struct Mystruct B TPS 1012 Usually there is no need to use both tag and typedef either can be used in struc ture type declarations Untagged structure and union members are ignored during initialization Note See also Working with structures MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 163 CHAPTER 5 Language Reference mikroC for 8051 WORKING WITH STRUCTURES Structures represent user defined types A set of rules regarding the application of structures is strictly defined Assignment Variables of the same structured type may be assigned one to another by means of simple assignment operator This will copy the entire contents of the variable to destination regardless of the inner complexity of a given structure Note that two variables are of the same structured type only if they are both defined by the same instruction or using the same type identifier For example a and b are of the same type struct int ml m2 a b But and d are not of the same type although their structure descriptions are identical struct int ml struct int ml m2 Size of Structure The size of the structure in memory can be retrieved by means of the operator size of It is not necessary that the size of the

Download Pdf Manuals

image

Related Search

Related Contents

Fisherr FIELDVUE™ DVC6200デジタルバルブ コントローラ  TP-LINK TL-R460 router  Garden Notepad Plus Manual - BG-Map  Toshiba Qosmio X70-AST2GX1  HeartSine 350P - Trainer User Manual  Cables Direct UT-8824 patch panel  Du nouveau – le fongicide LanceMC pour les petits  Journéesdes Entrepreneurs du Voyage  Tanco Autowrap 1300 S & SM Bedienerhandbuch WD66-1300  Toshiba 80GB SATA HDD  

Copyright © All rights reserved.
Failed to retrieve file