Home
mikroC PRO for AVR User`s Manual
Contents
1. 56R L4 1 gt RO 8 Z De 1 VCC 5 4K7 OSCILLATOR i LTC485 gt VCC 4K7 56R 56R 1 7 8 RO 7 6 5 RE B DE 1 AKT LTC485 4 TuF 3 _ J J 4 7uF ve enp c2 z R1IN JH e azr PUY T2out N Tain R2in R2out RTS Aur GND RX Ik N gt Example of interfacing PC to AVR MCU via RS485 bus with LTC485 as RS 485 transceiver 400 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR 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 0 9 bit7 1 MASTER SENDS 0 SLAVE SENDS bit6 1 ADDRESS W
2. 213 For Statement 222 dibus ree Pha dod deh bs bbe te qus 214 Jump Statements 215 Break and Continue Statements 215 Break Statement idee fod Sl tote Peele Sian 215 Continue 215 Goto Statement 2 s 216 Return 217 Compound Statements Blocks 217 i vind ape Bh WG AUR RUE HU T UR 218 Preprocessor Directives 219 Line Continuation with Backslash 219 CREMMERERME 220 Macros with Parameters 221 Undefining 222 File INCISION ur ierat a e Rb E DEG ame 223 Explicit Path bm be e RR aene Pe 223 NOG i htc taeda eei ana AE EE 223 Preprocessor Operators 224 Operator 224 Operator FAP A CLE 224 ipt Gehan ha eee SS da eee dba 224 Conditional Compilation 225 Directives elif Helse a
3. 439 SPI Ethernet putBytes 439 SPI Ethernet putConstBytes 440 SPI Ethernet putString 440 SPI Ethernet putConstString 441 SPI Ethernet getByte 441 SPI Ethernet getBytes 442 443 SPI Ethernet UserUDP 444 Library Example sss ubl as ee REED ane Dae TR 444 HW Connection 452 SPI Graphic Lcd Library 1 453 External dependencies of SPI Graphic Lcd Library 453 Library Routines usse eG ee GE e RS 453 SPI Gled Init i oe end age oa Mee Ernte RR Re Re 454 SPI Glcd Set 455 SPI Gled Set Page 455 SPI Gled Set X ans 804 eas 456 456 457 SPI Gled Fill Pen HR 457 Dot 06 Med VERRE ERR 458 SPI Gled Line oss res en eee In ae 458 XXII MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS
4. NERA RU aed ARE ODE RD nts 571 enr 571 Library 572 Time LIDramy 222 rebar eh PR dd 573 Library Routines 573 Time dateToEpoch 573 Time epochToDate 574 _ 575 Library Examples ose ceca ge cheba Ca ee ee YER 576 Trigonometry Library 2 1 577 Library Routines 577 SINES aoe a oe ET gee Gas euer die 577 COSES ta DR ye eee ee ee 578 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XXIX Table of Contents mikroC PRO for AVR XXX MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER Introduction to mikroC PRO for AVR The mikroC PRO for AVR is a powerful feature rich development tool for AVR micro controllers It is designed to provide the programmer with the easiest possible solu tion to developing applications for embedded systems without compromising per formance or control CHAPTER 1 Introduction mikroC PRO for AVR LN 383232228 5 LOG ATA 45 lt 11111114 A
5. 153 Enumeration Scope 153 SI E 154 Void Functions s e ROC ds 154 Generic Pointers 154 Derived Types eases ga ere ae a a ea ed e te NR e eR tue 155 AITAYS cole id b ids 155 Array Declaration 155 Arrays in Expressions 156 Multi dimensional Arrays 156 mgl T 158 Pointer Declarations 158 N ll POlDtelS san OR SEO ae qe Mk Rd E a 159 Function Polnters 2 22 22 22211 44 160 Assign an address to a Function Pointer 160 Pointer 161 Arrays and 5 161 Assignment and Comparison 162 Pointer Addition bea beu ee VEU d 163 Pointer Subtraction 164 Structures 2 qu aioe 165 Structure Declaration and Initialization 165 Untagged Structures and 166 Working with Structures 167 ASSIGNMENT
6. 421 External dependencies of Sound Library 421 Library ROUtIMES 2 22 2 ee RR UR Ra 421 Sound HIN a eddie eed e eda ae 422 Sound Play esl ke ERR RE IRURE RI RR eee 422 Library Example vies sac RR RR RR RE 423 HW Connection exc ees Pee x EUR EU RR RO 425 SPI Libraty ssi d ee dedu an dde pg qb dies 426 Library RoutineS 426 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XXI Table of Contents mikroC PRO for AVR 426 SPM Init Advanced 427 REA coe HAG RR ao RR eh RR 428 Write ud DER obedece diea Deci tees 428 Library 429 HW Connection 430 SPI Ethernet Library sea cercas ceca ee a RR ERR REX 431 External dependencies of SPI Ethernet Library 432 Library RoutineS 433 SPI Ethernet 434 SPI Ethernet 436 SPI Ethernet 437 SPI Ethernet doPacket 438 SPI Ethernet
7. 531 Sat 2 5 fie io EISE eoe ecol ae 531 Read 552 EXER ead ER 531 ce Re ERE 532 50 pm RR X EON X AUREOS CERERI a GR eO S 532 INCUMBIT 532 DUCI ETT 532 Library 533 HW Connection 533 UART LEIDraby sucum ach Sam ocr oe A adn Rade acs de wad gad ead Sealy 534 Library RoutineS 922 2000 cse Oe 534 UARTX IINIT dicere ie eben ieee 535 UARTx Init Advanced 536 _ 537 537 UARTx Read Text 538 Write uie opu add Ee ene wok Rep An os e LO Res 539 UARTx Write Text 539 Library Example 22x rde Dues mde De is 540 HW Connection 541 ANSI C Ctype Library 2 ce seed d RAE 542 Library Functions 542 2er ROERRE AR DO ERA ERR Ree 542 isalpha ee UR Ae TR TR eda 542 LER EE QS 542 PET 543 ISgrapli ise even
8. 327 Mmc Fat 328 Mmc Fat ASSIgt ue zou ea UE deg qve Kaa 329 Mmc Fat Reset 330 Mime 5242 Reb Ex Ree d RE CERE ES 330 Mmc Fat Append 330 Minic Fat Read uen a Le e LR ae es 331 Mmc Fat Delete 331 Mmc Fat Write 331 Mmc Fat Set _ 332 Mmc Fat Get File 332 Mmc Fat Get File 333 Mmc Fat Get 334 XVIII MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Table of Contents Library 2 20 24 rb reram diese feet 335 HW Connection 346 OneWire Library ee ee ee eee EE 347 External dependencies of OneWire 347 Library RoutineS 348 Ow Reset ies denice aioe eel a aa eee AAA es 348 OW Read o 2 42 saan aed eee wo a n 349 2 ET 349 Library Example ene e ena eee 350 HW Connection 352 Port Expander Library 22222544545
9. PORTD B4 PORTD B5 PORTD B6 PORTD B7 PORTD B2 PORTD B3 LCD 2X16 4x4 Keypad connection scheme 304 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR LCD LIBRARY CHAPTER 6 Libraries The mikroC PRO for AVR provides a library for communication with Lcds with HD44780 compliant controllers through the 4 bit interface An example of Lcd con nections is given on the schematic at the bottom of this page For creating a set of custom Lcd characters use Lcd Custom Character Tool External dependencies of Lcd Library The following variables must be defined in all proj ects using Lcd Library extern sfr sbit extern sfr sbit extern sfr sbit extern sfr sbit extern sfr sbit extern sfr sbit extern sfr sbit D RS Direction sfr sbit Direction sfr sbit Direction sfr sbit Direction sfr sbit _Direction sfr sbit Direction Description Register Select line Enable line sbit PORT _D7 at at at D4 at Register Select direc tion pin Enable direction pin Data 7 direction pin Data 6 direction pin Data 5 direction pin Data 4 direction pin Direction Direction Direction Direction Direction Direction MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 305 CH
10. MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 487 CHAPTER 6 Libraries mikroC PRO for AVR SPI_T6963C_WaitReady Prototype SPI T6963C WaitReady void Pools the status byte and loops until Toshiba Glcd module is ready Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example wrrex eeu 000000000 SPI T6963C Fill void SPI T6963C Fill unsigned char v unsigned int start Prototype unsigned int len Fills controller memory block with given byte Parameters Description v byte to be written start Starting address of the memory block len length of the memory block in bytes Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example srreecruressmeemwmen 0 SPI T6963C Dot Prototype void SPI T6963C Dot int x int y unsigned char color Draws a dot in the current graphic panel of Glcd at coordinates x y Parameters Description x dot position on x axis y dot position on y axis color color parameter Valid values T6963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example SPI T6963C Dot x0 yO pcolor 488 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI_T6963C_Write_Char Prototype Description void SPI T6963C Write Ch
11. 476 External dependencies of SPI Lcd Library 476 Library Routines 476 SPI Lcd8 0 477 SPI Ledo Out ci REA 478 SPI Lede Cp loved RAE Fe a ERR es X Mae 478 SPI LEJE CHE tetuer LESu E RR E LER REA 479 Ledg Cp iode e Rad itd a hei hd 479 SPI Leda i bo ee ee ues peer iet Ree 480 Available Lcd Commands 480 Library Example mte m RC d 481 HW Connection eee 6 Fee EPA de 482 SPI T6963C Graphic Lcd 483 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XXIII Table of Contents mikroC PRO for AVR External dependencies of SPI T6963C Graphic Lcd Library 483 Library leu meme ed ae ae RR Ce a 484 SPI T6963C Config 485 SPI T6963C WriteData 487 SPI T6963C WriteCommand 487 769630 SetPlr RR RE RR RR 487 6963 488 6963 Fill 15 pr Rt Gra eee Read 488 SPI 6963
12. 514 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries T6963C_Line void T6963C Line int x0 int y0 int xl int yl unsigned char pcolor Draws a line from x0 yO to x1 y1 Prototype Parameters x0 X coordinate of the line start y0 y coordinate of the line end x1 X coordinate of the line start y1 y coordinate of the line end pcolor color parameter Valid values T6963C BLACK and T6963C WHITE Toshiba GLCD module needs to be initialized See the T6963C Init routine Eos em Line 0 0 239 T6963C WHITE T6963C Rectangle Description void 6963 Rectangle int x0 int y0 int xl int yl unsigned char pcolor Draws a rectangle on GLCD Prototype Parameters x0 X coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values 6963 BLACK and T6963C WHITE Toshiba GLCD module needs to be initialized See the T6963C Init routine Example ser 20 213 um Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 515 CHAPTER 6 Libraries mikroC PRO for AVR T6963C_Box void T6963C Box int x0 int 0 int x1 int yl unsigned char pcolor Draws a box o
13. Ae ee eee ee 167 Sizo ot SUUCIUIO oss ese ERE REG PR ORIG REIR RR Re 4 167 Structures and 167 Structure Member Access 168 Accessing Nested Structures 169 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XI Table of Contents mikroC PRO for AVR Structure Uniqueness 169 WIIONS pP 170 Union Declaration 170 SIZE OF UNION 252 5826 Le ee 170 Union Member 5 170 Bit Fields taccSexe sedate doesn 172 Bit Fields 172 Bit Fields ACG SS reges gripe a ee hare Hee oe Rae RS 173 Types Conversions 174 Standard Conversions 175 Arithmetic Conversions 175 In details vic cad fe alma RII epee ie te dd awe eh teks 175 Pointer Conversions 176 Explicit Types Conversions 177 Declarations sssri aiie ara ice ac eR dea Rn 178 Declarations and Definitions 178 Decla
14. 105 Built in 106 ce sient EU EE 106 RR CRT 107 HINE Pte ies 107 Highest iss xe bcd papaya eee 107 Delay us zz ida eae ee E Mo 108 Delay mS s xxm nua ese sed ee ese Reeds ERR Pees 108 Vdelay ims leemos ara um UE De ee tee 108 Delay EE 109 Clock KHZ est ud E ERG XE ERG EE ES 109 Clock MHZ iube d Re bee een a ERR 109 Get Fosc 2 110 Code Optimization 110 Constant folding Lex e Rd a bui Meat 110 Constant propagation 110 Copy propagation 110 Value numbering 110 Dead code ellimination 110 Stack allocation 111 VIII MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Table of Contents Local vars optimization 111 Better code generation and local optimization 111 CHAPTER 4 Types 113 Nested Calls Limitations 114 Important
15. 114 AVR Memory Organization 115 Program Memory 115 Data Memory 2 116 Memory Type Specifiers 117 COGO cu ER GEER TGR SHE owes guis ta anui 117 e Sant puc DN uU MIL ee Seas EE 117 X peda idu aud deser ied deba biu 118 orm 118 d Mv Tcr TEE 118 CHAPTER 5 mikroC PRO for AVR language Reference 120 Lexical Elements Overview 122 Whitespace e we te ged S 122 Whitespace in Strings 122 Line Splicing with Backslash 123 COMMENTS ERA RR RUN ROS AUR ARA EN OR 123 C comments E RC dE AUT E E a Rue 123 Crt comments 2 saw eddie RR ua os ARD 124 Nested comments 124 TOKENS eer 125 Token Extraction Example 125 e ICTU 126 Integer Constants 127 Long and Unsigned Suffixes 127 Decimal x be eee Re ee ple a ee ee ee 127 Hexadecimal 128 BINA gt i es pb cede EP
16. 9LVOANLV PWM demonstration MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 381 CHAPTER 6 Libraries mikroC PRO for AVR PWM 16 BIT LIBRARY CMO module is available with a number of AVR MCUs mikroC PRO for AVR pro vides library which simplifies using PWM HW Module Note For better understanding of PWM module it would be best to start with the example provided in Examples folder of our mikroC PRO for AVR compiler When you select a MCU mikroC PRO for AVR automaticaly loads the correct PWM 16bit library which can be verified by looking at the Library Manager PWM library han dles and initializes the PWM module on the given AVR MCU but it is up to user to set the correct pins as PWM output this topic will be covered later in this section Library Routines PWM 16bit_Init PWM16bit Change Duty PWM16bit Start PWM16bit Stop Predefined constants used in PWM 16bit library The following variables are used in Description PWM library functions ee T MODE 8BIT Selects Phase Correct 8 bit mode Selects Phase Correct 9 bit mode E 10BIT Selects Phase Correct 10 bit mode Selects Fast 8 bit mode Selects Fast 9 bit mode Selects Fast 10 bit mode Sets prescaler value to 1 No prescal ing Sets prescaler value to 8 ibit 64 Sets prescaler value to 64 l6bit 256 Sets prescaler value to 256 382 MIKROELEKTRONIK
17. de Ree Ted ed ww dd ean 193 Operators Precedence and 194 Arithmetic Operators 195 Arithmetic Operators Overview 195 Binary Arithmetic 5 195 Unary Arithmetic Operators 196 Relational Operators 197 Relational Operators Overview 197 Relational Operators in Expressions 197 Bitwise Operators 198 Bitwise Operators Overview 198 Logical Operations on Bit 198 Bitwise Shift Operators 199 Bitwise vs 199 Logical Operators 1225524 Pad aed eed 200 Logical Operators Overview 200 Logical Operations 200 Logical Expressions and Side Effects 201 Logical vs Bitwise 201 Conditional Operator 202 Conditional Operator Rules 202 Assignment Operators
18. aa O MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 513 CHAPTER 6 Libraries mikroC PRO for AVR T6963C_Write_Text Prototype Description Requires void T6963C Write Text unsigned char str unsigned char unsigned char y unsigned char mode Nothing Writes text in the current text panel of GLCD at coordinates x y Parameters str text to be written x text position on x axis y text position on y axis mode mode parameter Valid values T963C 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 combin ing text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in the negative mode i e white text on black background AND Mode The text and graphic data shown on display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Toshiba GLCD module needs to be initialized See the T6963C Init routine T6963C Write Text GLCD LIBRARY D T6963C ROM MODE XOR
19. 203 Simple Assignment 203 Compound Assignment Operators 203 Assignment Rules 2222222 22 42 42 4 44 204 Sizeof Operator 205 Sizeof Applied to Expression 205 Sizeof Applied to 205 EXPreSSIONS a 2 446 ae RR RR EE xe EG Eee aq CR a RR 206 Comma Expressions 207 NOIE RO as 207 Statements PER 208 Labeled 5 208 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XIII Table of Contents mikroC PRO for AVR Expression Statements 209 Selection Statements 209 If Statement 2 We a 210 Nested If statements 210 6 2 5 Mea tee ead gee wee hee 210 Switch Statement issus ev RERO ee ee ee 211 Nested switch 212 Iteration Statements Loops 212 While Statement crue LER NRI IHRER ce 212 Do
20. EA VCC PORTA Port Expander HW connection gt m E 6 Libraries 0 ze 365 CHAPTER 6 Libraries mikroC PRO for AVR PS 2 LIBRARY The mikroC PRO for AVR provides a library for communication with the common PS 2 keyboard Note The library does not utilize interrupts for data retrieval and requires the oscil lator clock to be at least 6 2 Note The pins to which a PS 2 keyboard is attached should be connected to the pull up resistors Note Although PS 2 is a two way communication bus this library does not provide MCU to keyboard communication e g pressing the Caps Lock key will not turn on the Caps Lock LED External dependencies of PS 2 Library The following variables must be defined in all projects using Description Manchester Code Library sbit PS2 Data at f it PS2 Data extern sfr sbit PS2 Data PS 2 Data line extern sfr sbit eee sbit PS2 In Clock extern sfr sbit sbit PS2 Out Clock PS2 Out Clock 5 2 Clock line out at PORTC B1 extern sfr sbit Direction of the PS 2 PS2 Data Direction Data pin Data Direction DDRC B0 extern sfr sbit Direction of the PS 2 PS2 Clock Direction Clock pin Clock Direction at DDRC B0 Library Routines Ps2 Config Ps2 Key Read 366 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Ps2_Config Initializes the
21. Pe UR ee 488 SPI T6963C Write Char 489 6963 490 SPI T6963C 491 SPI T6963C Rectangle 491 SPI T6963C BOX bead Vb I d ee AGE E 492 6963 492 SPI T6963C Image 493 SPI T6963C 5 493 SPI T6963C Set Cursor 494 5 1_ 6963 _ 494 SPI T6963C 495 5 1_ 6963 _ 495 SPI T6963C 496 SPI T6963C DisplayTxtPanel 496 SPI T6963C SetGrPanel 496 6963 497 SPI T6963C PanelFill 497 SPI T6963C 497 SPI 6963 6 dead doped REM ERROR Ra 498 6963 498 SPI_T6963C_Graphics 498 6963 Text 22222222 4 2524 4
22. UARTx_Read Prototype Returns Returns the received byte er Function receives a byte via UART Use the function UARTx_Data_Ready to Description test if data is ready first Requires UART HW module must be initialized and communication established before q using this function See UARTx Init If data is ready read it if UART1 Data Ready 1 receive VARTI Read MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 537 CHAPTER 6 Libraries mikroC PRO for AVR UARTx_Read_Text Prototype Description void UARTx Read Text char Output char Delimiter char Attempts Nothing Reads characters received via UART until the delimiter sequence is detected The read sequence is stored in the parameter output delimiter sequence is stored in the parameter delimiter This is a blocking call the delimiter sequence is expected otherwise the proce dure exits if the delimiter is not found Parameterv Attempts defines number of received characters in which Delimiter sequence is expected If Attempts is set to 255 this routine will continuously try to detect the Delimiter sequence UART HW module must be initialized and communication established before using this function See UARTx Init Read text until the sequence OK is received and send back what s been received UART1 Init 4800 initialize UART module Delay ms 100 while 1 if UART1 Data Read
23. from the Code Toolbar Spell Checker The Spell Checker underlines unknown objects in the code so they can be easily noticed and corrected before compiling your project Select Tools Options from the drop down menu or click the Show Options Icon at and then select the Spell Checker Tab Bookmarks Bookmarks make navigation through a large code easier To set a bookmark use Ctri Shift number To jump to a bookmark use Ctri number Goto Line The Goto Line option makes navigation through a large code easier Use the short cut Ctrl G to activate this option Comment Uncomment Also the Code Editor has a feature to comment or uncomment the selected code by simple click of a mouse using the Comment Icon and Uncomment Icon from the Code Toolbar 44 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR CODE EXPLORER The Code Explorer gives clear view of each item declared inside the source code You can jump to a declaration of any item by right clicking it Also besides the list of defined and declared objects code explorer displays message about first error and it s location in code Code Explorer 2 4L 4 Functions main Globals TypeDef Tags Includes CHAPTER 2 Environment Following options are available in the Code Explorer Icon Description m Expand Collapse all nod
24. Pare ee qao Warn aT doe ale 543 543 iniu cL Lee rp MM 543 155 gt 543 ISUDDOT a 543 ISXdlglt duce age 543 touppet icq RR eb Rev 544 CETT 544 XXVI MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Table of Contents ANSI C Math Library is cp ae aaa gee Sea Reb RD E eed 545 Library FUNCHONS 4 ner spe ee ee 545 M PIC cT CE 546 ASIN a I A rp PLC ELE 546 AIAN PRI 546 2 REY Re eae ewe a RAE ER 546 CT 546 COS PP PE 546 wolle P DE 547 eval poly 547 Du Git abbas dee nad nd 547 Ico 547 HOOF META EET 547 rexpiseci otros LLLI Mt S 547 hd PEE 547 lOg idit stole doe eta rues Lara PACEM dp 548 icr mx E ERR ER ERR CR pene 548 modf a teg ares 548 DOW 22224 Da a ae ae aed Ve aos 548 E 548 Se S cL 548 548 AA e at ai hale ace RT aha OR are 549 Ich eC 549 ANSI C Stdlib 550
25. D eee RP dde Ra qu ede 366 Ps2 Key Read sse vas er REN RA ERR RA 366 Ps2 Contig onse eser dde 367 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XIX Table of Contents mikroC PRO for AVR Ps2 Key Read 368 Special Function 369 Library Example cssc ee a ee a s 370 HW CONDECION beat Ruhr 371 PWM Library ise rat AERE REGE ERE rA EE 372 Library Routines issus TRA REY TRE Vaated ene ewe 372 Predefined constants used PWM library 372 PWM Int 2 eerte ree nt et raton Rene er ane Papeete 374 PWM Set 376 PWM Start umo tme Ga eae iR ek X Us ca aed i Us Lg way 376 PWM SOP tete be edis bob ae debet Eb ae tle 376 PWMT qs 377 PWMT Set DUY s oec ue Re e Ge ER 379 PWM Statt IR or dedere aides 379 PWMT SIOD erac x Rete rte Rr etm IET doa e Ros ER eae eG aedes 379 Library Example 2252 5255 REUTERS 380 HW Connection 2 1 381 PWM 16 bit Library 2 p24 lb Een ad herd Re EUR 382 Library RoutineS 382 Predefined constants used in PWM 16bit library 382 PWMn19bi
26. MSG CANSPI CONFIG PHS CANSPI CONFIG XTD MSG amp CANSPI CONFIG DBL BUFFER ON amp CANSPI CONFIG VALID XTD SPI1 Init Spi Rd Ptr SPI1_ Read pass pointer to SPI Read function of used SPI module Init CANSPIInitialize 1 3 3 3 1 Can Init Flags initialize external CANSPI module CANSPISetOperationMode CANSPI MODE CONFIG set CONFIGURATION mode CANSPISetMask CANSPI MASK 1 1 set all maski bits to ones CANSPISetMask CANSPI MASK B2 1 set all mask2 bits to ones CANSPISetFilter CANSPI FILTER B2 F4 3 initialize SPI1 module CANSPI CONFIG XTD MSG CANSPI CONFIG XTD MSG CANSPI CONFIG XTD MSG set id of filter B1 F1 to 3 CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode RxTx Data 0 9 set initial data to be sent Tx ID 12111 set transmit ID CANSPIWrite Tx ID RxTx Data 1 Can Send Flags send initial message while 1 endless loop Msg Rcvd amp Can Rcv Flags CANSPIRead amp Rx ID receive message Le Rx ID if message received check id 3u PORTC Lh output data at PORTC id correct increment received data Delay ms 10 CANSPIWrite Tx ID send incremented data back RxTx Data RxTx Data amp Rx Data Len amp amp Msg Rcvd RxTx Datal 0 RxTx Data 0 E 1 Can Send Flags 248 MIKROELEKTRONIKA SOFTWARE AND HARDWARE
27. 517 16963C Set Cursor deed dead 518 6963 518 6963 ee BE dE 519 T6963C 519 T6963C 520 T6963C DisplayTxtPanel 520 T6963C SetGrPanel 521 16963C SetIxtPanel inse Iam Res Re Rid E 521 T6963C PanelFill 522 T6963C_GrFill 522 169639 2242 der che eed Ee dedu 522 6963 523 T6963C esset GS re Ew i 523 T6963C Text oeste edie dd ve or eee teat eae 523 11696306 GUISOF i sues oe ue anm n D 524 T6963C Cursor 524 Library Panes ee wad en wages 525 HW Connection 529 TWI Library ollm edie 530 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XXV Table of Contents mikroC PRO for AVR Library Routines 2n sepas ck pees deer dd 530 TWI a E Hte n RE nS e 530 DRUMS aerer ae
28. Pe dad 278 FLASH Read Byte 278 FLASH Read Bytes 279 FLASH Read Word 279 FLASH Read Words 280 Library Example nae he ew a Ex aa ee 280 Graphic LCD Library 282 External dependencies of Graphic LCD Library 282 Library RoutineS 283 XVI MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Table of Contents Gled Inlt oi ene erbe ete wa wha eed 284 Gled Set SIde ei pac Aa ae ee ee a 285 Civis ir AEEA EEE 285 Set Page 286 _ _ 286 Write Data ve ERR a Ra Rae ES 287 uie e at de aoe eee Wages x CR a gaia A 287 Gled e Rr Eee Roter eene eae ate eR etn as 288 Gled Lille onc pa pae en pred PR A A 289 Gled V Line owe dee 289 Gled ebbe eb ebbe ead ddan d oe 290 Rectangle s ice RR RR RE Rn 290 5 E 291 GledvCiele i ede WE eee 291 Gled Set Foni uiae kac aly eed Ge 2
29. Port Expander mod sbit SPExpanderRST sbit SPExpanderCS sbit SPExpanderRST sbit SPExpanderCS D End Port Expander If Port Expander ING Initialize SPI Rd Ptr SPI1 Read Pass pointer to SPI Read function of use SPI Glcd Init 0 SPI module used with PortExpander d SPI module 454 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI Glcd Set Side Prototype void SPI Glcd Set Side char x pos Nothing Selects Glcd side Refer to the Glcd datasheet for detail explanation Parameters x pos position on x axis Valid values 0 127 Description The parameter x specifies the Glcd side values from 0 to 63 specify the left side values from 64 to 127 specify the right side Note For side x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see SPI Glcd Init routines The following two lines are equivalent and both of them select the left side of Glcd SPI Set Side 0 SPI Gled Set Side 10 SPI Glcd Set Page Prototype void SPI Glcd Set Page char Selects page of Glcd Parameters Deseription page page number Valid values 0 7 Note For side x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see SPI_GIcd
30. init display for 240 pixel width 128 pixel height 8 bits character width data bus on MCP23S17 portB control bus on 23517 portA bit 2 is WR bit 1 is RD bit 0 is CD bit 4 rs RST chip enable reverse on 8x8 font internaly set in library ay Pass pointer to SPI Read function of used SPI module SPI_Rd Ptr SPI1 Read Initialize SPI module SPI1_ Init Advanced SPI MASTER SPI FCY DIV32 SPI HI TRAIL ING If Port Expander Library uses SPI2 module Pass pointer to SPI Read function of used SPI module SPI Rd Ptr SPI2 Read Pass pointer to SPI Read function of used SPI module Initialize SPI module used with PortExpander SPI2 Init Advanced SPI MASTER SPI FCY DIV32 SPI CLK HI TRAILING Initialize SPI Toshiba 240x128 SPI T6963C Config 240 128 8 0 2 1 0 4 Delay ms 1000 Enable both graphics and text display at the same time SPI T6963C graphics 1 SPI T6963C text 1 panel 0 i curs 0 cposx cposy 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 501 CHAPTER 6 Libraries mikroC PRO for AVR Text messages ay SPI T6963C write text txt 0 0 SPI T6963C ROM MODE XOR SPI T6963C write text txtl 0 15 SPI T6963C ROM MODE XOR Cursor ia SPI T6963C cursor height 8 8 pixel height SPI T6963C set cursor 0 0 move curs
31. data byte to be written The corresponding MCU ports must be appropriately initialized for CF card See Cf Init CF card must be initialized for writing operation See Cf Write Init char data OxAA Cf Write Byte data MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 257 CHAPTER 6 Libraries mikroC PRO for AVR Cf_Read_Sector void Cf Read Sector unsigned long sector number unsigned short buffer Reads one sector 512 bytes Read data is stored into buffer provided by the buffer parameter Prototype Description Parameters sector number Sector to be read buffer data buffer of at least 512 bytes in length 4 MCU ports must be appropriately initialized for CF card See read sector 22 unsigned short data 512 Cf Read Sector 22 data Cf_Write_Sector void Cf Write Sector unsigned long sector number unsigned short buffer Writes 512 bytes of data provided by the buffer parameter to one CF sector Prototype Parameters Description sector number Sector to be written to buffer data buffer of 512 bytes in length MCU ports must be appropriately initialized for CF card See write to sector 22 unsigned short data 512 Cf Write Sector 22 data 258 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Cf Fat Init Prototype unsigned short Cf Fat Init
32. 286 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Glcd Write Data Prototype void Glcd Write Data unsigned short ddata Nothing Writes one byte to the current location in Gled memory and moves to the next location DeseripHon Parameters ddata data to be written Glcd needs to be initialized see Glcd Init routine Glcd side x axis position and page should be set first See functions Set Side Glcd Set X and Glcd Set Page unsigned short data Glcd Write Data data Glcd Fill Prototype void Fill unsigned short pattern Fills Glcd memory with the byte pattern Parameters Description pattern byte to fill Glcd memory with To clear the Glcd screen use Glcd_Fill 0 To fill the screen completely use Glcd_Fill 0xFF Glcd needs to be initialized see Glcd Init routine Clear screen Gled Fill 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 287 CHAPTER 6 Libraries mikroC PRO for AVR Glcd Dot id Glcd Dot i d short i d short Prototype void cd Dot unsigned short x pos unsigned short y pos unsigned short color 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 Description color color parameter Valid values 0 2 The parameter color determines a dot state
33. Draw image delay2S delay2S Gled Fill 0x00 Clear Glcd Glcd Box 62 40 124 56 1 Draw box Glcd Rectangle 5 5 84 35 1 Draw rectangle Glod Line 0 0 127 63 1 Draw line 1 25 for ii 5 lt 60 5 Draw horizontal and vertical lines Delay ms 250 Glcd V Line 2 54 ii 1 Glcd H Line 2 120 ii 1 delay2S 1 Fill 0x00 Clear Glcd Glcd Set Font Character8x7 8 7 32 Choose font see Lib GLCDFonts c in Uses folder Glcd Write Text mikroE 1 7 2 Write string for ii 1 ii lt 10 ii Draw circles Glod Circle 63 92 3 i 1 7 1 25 Gled 12 20 70 51 2 7 Draw box delay28 Glcd Fill OxFF Fill Glcd 296 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD G S G G d G S G G lcd Set Font Character8x7 8 7 32 omeText 8x7 Font lcd Write Text someText 5 0 2 Li lcd Write Text someText 5 1 2 2 1 25 led Set Font System3x5 3 5 32 omeText 3X5 CAPITALS ONLY lcd Write Text someText 60 5 2 lcd Write Text someText 60 6 2 Lf 1 25 led Set Font font5x7 5 7 32 gu omeText 5x7 Font led Write Text someText 5 5 2 A lcd Write Text someText 5 6 2 1
34. Initialize SPI module used with PortExpander SPI Rd Ptr amp SPI2 Read Pass pointer to SPI Read function of used SPI module Expander Init 0 Initialize Port Expander Expander Set DirectionPortA 0 0x00 Set Expander s PORTA to be output Expander Set DirectionPortB 0 0xFF Set Expander s PORTB to be input Expander Set PullUpsPortB 0 0xFF Set pull ups to all of the Expander s PORTB pins while 1 Endless loop Expander Write PortA 0 i Write i to expander s PORTA PORTC Expander Read PortB 0 Read expander s PORTB and write it to LEDs Delay ms 100 364 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR HW Connection MCP23817 GPBO GPA7 2 GPB1 GPA6 3 GPB2 GPA5 4 GPB3 GPA4 5 GPB4 GPA3 GPB5 GPA2 7 8 GPB6 GPA1 GPB7 GPAO VCC 9 59 VDD INTA l INTB PB 1 11 SS RESET PB 7 12 cS SCK A2 PB 5 13 SI A1 PB 6 1 so AO 18 0 OSCILLATOR MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
35. RETURN HOME _CURSOR_OFF _UNDERLINE_ON LINK CURSOR E CURSOR Ll CD MOVE CURSOR RIGHT LCD TURN O LCD TU TURN OFF LCD SHIFT LEFT LCD SHIFT RIGHT Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 473 CHAPTER 6 Libraries mikroC PRO for AVR Library Example This example 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 PORTB BO sbit SPExpanderCS at PORTB B1 sbit SPExpanderRST Direction at DDRB B0 sbit SPExpanderCS Direction at DDRB B1 End Port Expander module connections void main If Port Expander Library uses SPI1 module SPIL Init r used with PortExpander SPI Rd Ptr SPI1 Read function of used SPI module If Port Expander Library uses SP SPI2 Init used with PortExpander SPI Rd Ptr SPI2 Read function of used SPI module SPI Lcd Config 0 interface SPI Lcd Cmd Lcd CLEAR SPI Lcd Cmd Lcd CURSOR OFF SPI Led Out l 6 miktoE row 6th column SPI Lcd Chr SPI Out 2 1 text row ist column SPI_Led_Out 3 1 mikroE two rows SPI Lcd Out 4 15
36. RS485Slave Init char Slave address Description Initializes MCU as a Slave for RS 485 communication Parameters Slave address Slave address Global variables R8485 rxtx pin this pin is connected to RE DE input of RS 485 transceiver see schematic at the bottom of this page RE DE signal controls RS 485 transceiver operation mode Valid values 1 for trans mitting and o for receiving 5485 rxtx pin direction direction of the RS 485 Transmit Receive pin must be defined before using this function UART HW module needs to be initialized See UARTXx Init RS485 module pinout sbit RS485 rxtx pin at PORTD B2 transmit receive control set to PORTC Bit2 Pin direction sbit RS485 rxtx pin direction at DDRD B2 RxTx pin direction set as output Pass pointers to UART functions of used UART module UART Wr Ptr UART1 Write UART Rd Ptr UART1 Read UART Ptr UART1 Data Ready UART TX Idle Ptr UART1 TX Idle UART1 Init 9600 initialize UART1 module RS485Slave Init 160 intialize MCU as a Slave for RS 485 communication with address 160 394 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries RS485Slave_Receive Prototype RS485Slave Receive char data buffer Nothing Receives messages from Master If Slave address and Message address field don t match then the message will be discarded
37. Small delay to avoid deboucing effect current dutyl t Increment duty ratio PWMl6bit Change Duty current dutyl CH B Set incremented duty 388 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries else if PINC B3 Detect if PORTC pin 3 is pressed Delay ms 40 Small delay to avoid deboucing effect current dutyl Decrement duty ratio PWM16bit Change Duty current dutyl _TIMER1 CH B Set decremented duty ratio while 1 Endless loop HW Connection gt m 2 Co PWM demonstration MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 389 CHAPTER 6 Libraries mikroC PRO for AVR RS 485 LIBRARY RS 485 is a multipoint communication which allows multiple devices to be connect ed to a single bus The mikroC PRO for AVR provides a set of library routines for comfortable work with RS485 system using Master Slave architecture Master and Slave devices interchange packets of information Each of these packets contains synchronization bytes CRC byte address byte and the data Each Slave has unique address and receives only packets addressed to it The Slave can never ini tiate communication It is the user s responsibility to ensure that only one device transmits via 485 bus at a time The RS 485 routines require the UART module Pins of UART
38. Fat Init Tries to create a swap file whose size will be at least 100 sectors If it succeeds it sends the No of start sector over UART void M Create Swap File size Mmc Fat Get Swap File 100 if size lt gt 0 ART Write ART Write Lo size ART Write Hi size ART Write Higher size ART Write Highest size ART Write OxAA Library Example MNC library test Upon flashing insert MMC SD card into the module when you should receive the Init OK message Then you can experiment with MMC read and write functions and observe the results through the terminal Receive Panel win dow MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 335 CHAPTER 6 Libraries mikroC PRO for AVR if defined we have a debug messages on PC terminal define RS232 debug 1 sbit Mmc Chip Select at PORTG B1 sbit Mmc Chip Select Direction at DDRG B1 universal variables unsigned int px k universal for loops and other stuff Variables for MMC routines unsigned char dData 512 Buffer for MMC sector reading writing unsigned char data for registers 16 buffer for CID and CSD reg isters RS232 communication variables unsigned char received character unsigned long sector address unsigned char first byte second byte third byte fourth byte unsigned char serial buffer 2 unsigned char serial pointer Display byte in hex vo
39. Formats date and time void Transform Time seconds seconds amp OxFO gt gt 4 10 seconds amp OxO0F Lf Transform seconds minutes minutes 6 OxF0 gt gt 4 10 minutes amp OxOF Transform months hours hours amp OxFO0 gt gt 4 10 hours amp OxOF Lf Transform hours year day amp 0 0 gt gt 6 Transform year day day amp 0x30 gt gt 4 10 day amp OxOF Transform day month month 8 0x10 gt gt 4 10 month amp OxOF Transform month a E Output values to LCD void Display Time Lcd Chr 1 6 day 10 48 Print tens digit of day variable Lcd Chr 1 7 day 10 48 Print oness digit of day variable Lcd Chr 1 9 month 10 48 Lcd Chr 1 10 month 10 48 Chr 1 15 year 56 Print year vaiable 8 start from year 2008 Led Chr 2 6 hours 10 48 Lcd Chr 2 7 hours 10 48 Lcd Chr 2 i minutes 10 48 Led Chr 2 1 minutes 10 48 Led Chr 2 y seconds 10 48 Lcd Chr 2 13 seconds 10 48 void Init Main Soft I2G Inst Led Init Lcd Cmd LCD CLEAR Lcd Cmd LCD CURSOR OFF Performs project wide init Initialize LCD Clear LCD display 77 Tarn cursor off Initialize Soft I2C communication CHAPTER 6 mikroC PRO for AVR Libraries pa eee Prepare and output static text on LCD Led Chr 1 8 i Led Ghe t 11 2 3 Lcd Out 2
40. Library Routines PWM Init PWM Set Duty PWM Start PWM Stop PWMI Init PWM1 Set Duty PWM1 Start PWM1 Stop Predefined constants used in PWM library The following variables are used in PWM library functions Description Selects Phase Correct PWM mode on first PWM library Selects Phase Correct PWM mode on sec ond PWM library if it exists in Library Man ager Selects Fast PWM mode on first PWM FAST library Selects Fast PWM mode second PWM library if it exists in Library Manager Sets prescaler value to 1 No prescaling 372 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR PRESCALER 256 PWM PRESCALER 1024 PWM1 PRESCALER 1 PWM1 PRESCALER 8 _PWM1_PR _PWM1_PR _PWM1_PR _PWM1_PRESCALER_256 _PWM1_PRESCALER_1024 _PWM_INVERTED _PWM1_INVERTED PWM NON INVERTED 1 NON INVE MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 Libraries Sets prescaler value to 32 this value is not available on every MCU Please use Code Assistant to see if this value is available for the given MCU Sets prescaler value to 64 Sets prescaler value to 128
41. MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 471 CHAPTER 6 Libraries mikroC PRO for AVR SPI Lcd Chr Prototype void SPI Lcd Chr char Row char Column char Out Char Prints character on Lcd at specified position Both variables and literals can be passed as character Parameters Description Row Writing position row number Column Writing position column number Out Char character to be written Lcd needs to be initialized for SPI communication see SPI Lcd Config routines Write character i at row 2 column 3 SPI Chr 2 3 749 SPI Lcd Chr Cp Prototype SPI Lcd Chr CP char Out Char Prints character on Lcd at current cursor position Both variables and literals can be passed as character Description Parameters Out Char character to be written Requires Lcd needs to be initialized for SPI communication see SPI Lcd Config routines Write character e at current cursor position SPI Lcd Chr Cp e 472 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR SPI Lcd Cmd CHAPTER 6 Libraries Sends command to Lcd Parameters Description out char command to be sent Note Predefined constants can be passed to the function see Available Lcd Commands Clear Lcd display SPI Lcd Cmd LCD CLEAR Lcd Command D FIRST ROW D SECOND ROW D THIRD ROW D FOURTH ROW CD CLEAR
42. TX cAN RS 2 1 4 GND vcco VCC CANL 4 RXD Vref MCP2551 ay ym p en e Shielded 1 twisted pair Example of interfacing transceiver 2510 with MCU via SPI interface 250 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries COMPACT FLASH LIBRARY The Compact Flash Library provides routines for accessing data on Compact Flash card abbr CF further in text CF cards are widely used memory elements com monly used with digital cameras Great capacity and excellent access time of only a few microseconds make them very attractive for microcontroller applications In CF card data is divided into sectors One sector usually comprises 512 bytes Routines for file handling the Cf_Fat routines are not performed directly but suc cessively through 512B buffer Note Routines for file handling can be used only with FAT16 file system Note Library functions create and read files from the root directory only Note Library functions populate both FAT1 and FAT2 tables when writing to files but the file data is being read from the FAT1 table only i e there is no recovery if the FAT1 table gets corrupted Note If MMC SD card has Master Boot Record MBR the library will work with the first available primary logical partition that has non zero size If MMC SD card has Volume
43. gt a amp amp lt z c 32 Conditional Operator Rules expressionl must be a scalar expression expression2 and expression3 must obey one of the following rules 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 is a structure or union type of expression and expression3 3 Both expressions have to be of void type The resulting type is void 4 Both expressions have to be of type pointer to qualified or unqualified ver sions of compatible types The resulting type is a pointer to a type quali fied with all type qualifiers of the types pointed to by both expressions 5 One expression is 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 6 One expression is a pointer to an object or incomplete type and the other is a pointer to a qualified or unqualified version of voia The resulting type is that of the non pointer to void expression 202 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference ASSIGNMENT OPERATORS Unlike many other programming languages C treats value assignment as operation represented by an operator r
44. 25 led Set Font FontSystem5x7 v2 5 7 32 omeText 5x7 Font v2 lcd Write Text someText 5 3 2 lod Write Text someText 5 2 2 delay2S Change font Write string Write string Change font Write string Write string Change font Write string Write string Change font Write string Write string CHAPTER 6 Libraries 297 CHAPTER 6 Libraries mikroC PRO for AVR HW Connection 0 Left side Right side X amp 9 paged 8 page 16 page2 page3 L page4 page5 page6 page7 Contrast vec Adjustment 10R MO O c oo ioo ee a ee OSCILLATOR j e d g 9LVOAWLV Glcd HW connection 298 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries KEYPAD LIBRARY The mikroC PRO for AVR provides a library for working with 4x4 keypad The library routines can also be used with 4x1 4x2 or 4x3 keypad For connections explana tion see schematic at the bottom of this page Note Since sampling lines for AVR MCUs are activated by logical zero Keypad Library can not be used with hardwares that have protective diodes connected with anode to MCU side such as
45. Add existing project to project group Remove existing project from project group Add File To Project Remove File From Project E Close current project Build Toolbar IY YET Build Toolbar comes with following options Icon Description Build current project Build all opened projects Build and program active project Start programmer and load current HEX file Open assembly code in editor View statistics for current project MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 23 CHAPTER 2 Environment mikroC PRO for AVR Debugger Eh er Debugger Toolbar comes with following options d Icon Description Start Software Simulator Run Pause debugger Stop debugger Step into Step over Step out Run to cursor Toggle breakpoint Toggle breakpoints Clear breakpoints View watch window View stopwatch window 5 LER See 24 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment Styles Toolbar Office 2003 Blue Soft sand Styles toolbar allows you to easily customize your workspace Tools Toolbar LE CA 4 Tools Toolbar comes with following default options Icon Description EJ Run USART Terminal EEP
46. 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 con nected to SPI module of MCU Prior to calling any of this library routines Spi_Rd_Ptr needs to be initial ized with the appropriate SPI Read routine 234 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries External dependecies of CANSPI Library The following variables must be defined in all proj Description ects using CANSPI Library extern sfr sbit sbit CanSpi CS at CanSpi CS Chip Select line PORTB BO extern sfr sbit Reset ling sbit CanSpi Rst at CanSpi Rst PORTB B2 extern sfr sbit Direction of the Chip Select Seer CanSpi CS Bit Direction CanSpi CS Bit Direction _ _ _ jpin at DDRB BO sbit extern sfr sbit i Direction of the Reset CanSpi Rst Bit Direction CanSpi Rst Bit Direction mee at DDRB B2 Library Routines CANSPISetOperationMode CANSPIGetOperationMode CANSPIInitialize CANSPISetBaudRate CANSPISetMask CANSPISetFilter CANSPIread CANSPIWrite The following routines are for an internal use by the library only RegsToCANSPIID CANSPIIDToRegs Be sure to check CANSPI constants necessary for using some of the fun
47. Draw a box between dots 5 15 and 20 40 Glcd Box 5 15 20 40 1 Glcd Circle void Glcd Circle int x center int y center int radius unsigned short color Nothing Draws a circle on Glcd Parameters x center X coordinate of the circle center Valid values 0 127 Description y center y coordinate of the circle center Valid values 0 63 radius radius size color color parameter Valid values 0 2 The parameter color determines the color of the circle line O white 1 black and 2 inverts each dot Requires Glcd needs to be initialized see Glcd Init routine Draw a circle with center in 50 50 and radius 10 Gred Cirele 50 50 10 l1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 291 CHAPTER 6 Libraries mikroC PRO for AVR Glcd_Set_Font Prototype void Glcd Set Font const char activeFont unsigned short aFontWidth unsigned short aFontHeight unsigned int aFontOffs Sets font that will be used with Glcd Write Char and Glcd_Write_Text routines Parameters activeFont font to be set Needs to be formatted as an array of char aFontWidth width of the font characters in dots aFontHeight height of the font characters in dots Description aFontOffs number that represents difference between the mikroC PRO for AVR character set and regular ASCII set eg if A is 65 in ASCII character and A is 45 in the mikroC PRO for AVR character set aF
48. Lcd Out Cp temp Lcd Chr Cp 223 degree character Led Che Use void as a function heading if the function does not take any parameters Alter natively you can just write empty parentheses main void same as main Generic Pointers Pointers can be declared as void which means that they can point to any type These pointers are sometimes called generic 154 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference 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 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 type array name constant expression This declares an array named as array name and composed of elements of type The type can be any scalar type except voia user defined type pointer enumer ation or another array Result of constant expression With
49. RS485Master_Receive RS485Master_Send RS485Slave_Init RS485Slave_Receive RS485Slave_Send RS485Master_Init Initializes MCU as a Master for RS 485 communication Global variables R8485 rxtx pin this is connected to RE DE input of RS 485 transceiver see schematic at the bottom of this page RE DE signal controls RS 485 transceiver operation mode Requires RS485 rxtx pin direction direction of the RS 485 Transmit Receive pin must be defined before using this function UART HW module needs to be initialized See UARTx_Init RS485 module pinout sbit RS485 rxtx pin direction at PORTC B2 transmit receive control set to PORTC Bit2 Pin direction sbit RS485 rxtx pin direction at DDRD B2 RxTx pin direction Set as output Pass pointers to UART functions of used UART module UART Wr Ptr UART1 Write UART Rd Ptr UART1 Read UART Ptr UART1 Data Ready UART TX Idle Ptr UART1 TX Idle UART1 Init 9600 initialize UART1 module RS485Master Init intialize MCU as a Master for RS 485 communication MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 391 CHAPTER 6 Libraries mikroC PRO for AVR RS485Master Receive Prototype void RS485Master Receive char data buffer 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 in t
50. Returns Returns 0 if read was successful or 1 if an error occurred 00 0 if read Returns 0 if read was successful or 1 if an error occurred successful or 1 if an error occurred eme ume reads CSD register and returns 16 bytes of content into Description data for registers Library needs to be initialized see Mmc Init bom rror Mmc Read Csd data 326 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Mmc_Fat_Init Prototype unsigned short Mmc Fat Init 0 if MMC SD card was detected and successfully initialized 1 if FAT16 boot sector was not found 255 if MMC SD card was not detected Initializes MMC SD card reads MMC SD FAT 16 boot sector and extracts neces Description sary data needed by the library Note MMC SD card has to be formatted to FAT16 file system Global variables Chip Select Chip Select line Mmc Chip Select Direction Direction of the Chip Select pin must be defined before using this function The appropriate hardware SPI module must be previously initialized See the SPI1 Init SPI1 Init Advanced routines MMC module connections sfr sbit Mmc Chip Select at PORTG B1 sfr sbit Mmc Chip Select Direction at DDRG B1 MMC module connections Pointer to appropriate SPI Read function 5 1 Init Advanced SPI MASTER SPI FCY DIV128 SPI CLK IO Li ING Spi Rd Ptr SPI1 Read use f
51. image files other files Note that the project does not include files in the same way as preprocessor does see Add Remove Files from Project New Project The easiest way to create a project is by means of the New Project Wizard drop down menu Project New Project or by clicking the New Project Icon Ry from Project Toolbar 76 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment New Project Wizard Steps Start creating your New project by clicking Next button Welcome to the New Project Wizard This wizard helps you e Create a new project e Select the device for your project e Setup device clock and choose device flags e Select desired memory model e Add project files Click Next to continue Step One Select the device from the device drop down list New Project Wizard Step 1 5 Select the device you want to use None gt Back Next gt Cancel MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 77 CHAPTER 2 Environment mikroC PRO for AVR Step Two Enter the oscillator frequency value New Project Wizard Step 2 5 Setup the clock for example 11 0592 MHz Back Next gt Step Three Specify the location where your project will be saved New Project Wizard Step 3 5 Specify where your project will be saved Project File Name
52. 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 CANSPIInitialize l 1 3 3 1 init initialize CANSPI 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 OxFD 1 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 CANSPI TX RTR FRAME OxBF XOXXXXXX You may use bitwise AND s to adjust the appropriate flags For example form value to be used as sending message flag send config CANSPI TX PRIORITY 0 amp CANSPI TX XTD FRAME 6 CANSPI TX NO RTR FRAME CANSPIWrite id data 1 send config MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 245 CHAPTER 6 Libraries mikroC PRO for AVR CANSPI_RX_MSG_FLAGS CANSPI RX MSG FLAGS are flags related to reception of CAN message If a par ticular bit is set then corresponding meaning is TRUE or else it will be FALSE const
53. k 3town 4tew M Stews 6tewn 76 M 2tewm Non Inverted Inverted The N variable represents the prescaler factor 1 8 64 256 or 1024 PWM 16bit_Init must be called before using other functions from PWM Library You need a CMO on the given MCU that supports PWM 16bit Before calling this routine you must set the output pin for the PWM according to the datasheet DDRB B1 1 set PORTB pin 1 as output for the PWM 16bit This code example is for ATmega168 for different MCU please consult datasheet for the correct pinout of the PWM module or modules Initialize PWM 16bit module PWMl6bit Init PWM16 PHASE PWM16 PRESCALER 16bit 8 CORRECT MODE 8BIT PWM16 NON INVERTED 255 385 CHAPTER 6 Libraries mikroC PRO for AVR PWM16bit Change Duty Prototype void PWMl16bit Change Duty unsigned duty unsigned short channel Nothing Changes PWM duty ratio Parameter duty takes values shown on the table below Where 0 is 096 and TOP value is 100 duty ratio Other specific values for duty ratio can be calculated as Percent TOP 100 Timer Counter Mode Update of TOVn Flag Set of Operation i OCRnX at on PWM Phase Correct OxOOFF BOTTOM 8 bit PWM Phase Correct Fast PWM 8 bit OxOOFF Fast PWM 9 bit 0x01FF Fast PWM 10 bit OxO3FF PWM module must to be initialised PWM 16bit_Init before using q PWM Set Duty funct
54. patt Equal to increments the pointer pa Increments the pointed object The following examples are also valid but better avoid this syntax as it can make the code really illegible a 1 i 3 a 1 i same as 3 i e ali i e 3 1 0 same as i 2 0 i e 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 162 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference Two pointers pointing to the same array may be compared by using relational oper ators lt lt gt and Results of these operations are the same as if they were used on subscript values of array elements in question int pa amp a 4 pb amp a 2 if pa pb won t be executed as 4 is not equal to 2 if 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 ineq
55. void SPI Ethernet Enable unsigned char enFlt Nothing This is MAC module routine This routine enables appropriate network traffic on the ENc28760 module by the means of it s receive filters unicast multicast broadcast crc Specific type of network traffic will be enabled if a correspon ding bit of this routine s input parameter is set Therefore more than one type of network traffic can be enabled at the same time For this purpose predefined library constants see the table below can be ORed to form appropriate input value Parameters enF1t network traffic receive filter flags Each bit corresponds to the appropriate network traffic receive filter const MAC Broadcast traffic receive filter flag When SPI Ethernet BRO set MAC broadcast traffic will be enabled ADCAST lxi MAC Multicast traffic receive filter flag When 5 Ethernet MUL UI ER RENE MAC multicast traffic will be enabled TICAST Er s eruat E FE po 0x40 not Inotused 0 20205050200 Iotused 2222 mne set unicast traffic will be enabled CAST Note Advance filtering available in the Nc28760 module such as Pattern Match Magic Packet and Hash Table can not be enabled by this routine Additionally all fil ters 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
56. 134 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference CONSTANT EXPRESSIONS A constant expressions can be evaluated during translation rather that runtime and accordingly may be used in any place that a constant may be Constant expressions can consist only of the following literals enumeration constants simple constants no constant arrays or structures sizeof operators Constant expressions cannot contain any of the following operators unless the operators are contained within the operand of a sizeof operator assignment comma decrement function call increment Each constant expression can evaluate to a constant that is in the range of repre sentable values for its type Constant expression can be used anywhere a constant is legal MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 135 CHAPTER 5 Language Reference mikroC PRO for AVR 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 PCL etc Probe the Code Assistant for specific letters Ctrl Space in Editor or refer to Pre defined Globals and Constants Here is an alphabetical listing of keywords in C asm auto break case Ghar
57. Deselect DAC chip void main InitMain Perform main initialization value 2048 When program starts DAC gives the output in the mid range while 1 Endless loop MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 429 CHAPTER 6 Libraries mikroC PRO for AVR if PINA BO amp amp value lt 4095 If PAO button is pressed value increment value else if PINA B1 amp amp value gt 0 If 1 button is pressed value Ff decrement value DAC_Output value Send value to DAC chip Delay ms 1 Slow down key repeat pace HW Connection Alllines are disconnected ee Vref line is connected Vcc line is connected R12 J10 1K 1 o VCC VCC rera gt 3 CON3 mmm E1 3 470uF 2 GND ma 7 w CN10 44 Ls ae vec DAC spi sck 3409 GND LG Aref CONNECTOR 5 41306 VREF US GND so MCP 4921 o gt m ve gt o SPI HW connection 430 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI ETHERNET LIBRARY The Nc28460 is a stand alone Ethernet controller with an industry standard Serial Peripheral Interface SPI It is designed to serve as an Ethernet
58. 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 Description sprintf char wh const char f The function returns the number of characters actually written to destination string sprintf is used to format data and print them into destination string Parameters wh destination string format string The argument is a format string and may be composed of characters escape sequences and format specifications Ordinary characters and escape sequences are copied to the destination string in the order in which they are interpreted Format specifications always begin with a percent sign and require additional arguments to be included in the function call The format string is read from left to right The first format specification encoun tered 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 and so on If there are more arguments than format specifica tions then these extra arguments are ignored Results are unpredictable if there are not enough arguments for the format specifications The format specifica tions have the following format flags w
59. P 1islegal 2 is undefined MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 163 CHAPTER 5 Language Reference mikroC PRO for AVR This allows you to write loops which access the array elements in a sequence by means of incrementing pointer in the last iteration you will have the pointer point ing to one element past the array which is legal However applying an indirection operator to a pointer to one past the last element leads to undefined behavior For example void f some type a int n function f handles elements of array a array a has n elements of type some type ine iz some type p amp a 0 for i 0r i lt nf Gee 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 ame TO int pil 0 int pi2 amp a 4 pi2 pil i equals 8 pis i gt gt 1 pi2 pi2 4 pi2 now points to 0 164 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference STRUCTURES A str
60. char mnth dat hrs mins file name MYFILEXXTXT Mmc Fat Assign file name mmc size Mmc Fat Get File Size MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 333 CHAPTER 6 Libraries mikroC PRO for AVR Mmc Fat Get Swap File Prototype Description unsigned long Mmc Fat Get Swap File unsigned long sectors cnt ehar filename char file attr Number of the start sector for the newly created swap file if there was enough free space on the MMC SD card to create file of required size 0 otherwise This function is used to create a swap file of predefined name and size on the MMC SD media If a file with specified name already exists on the media search for consecutive sectors will ignore sectors occupied by this file There fore it is recomended to erase such file if it exists before calling this function If itis not erased and there is still enough space for new swap file this function will delete it after allocating new memory space for new swap file The purpose of the swap file is to make reading and writing to MMC SD media as fast as possible by using the Mmc Read Sector and Mmc Write Sector functions directly without potentially damaging the FAT system Swap file can be considered as a window on the media where user can freely write read the data It s main purpose in mikroC s library is to be used for fast data acquisition when the time critical acquisition has f
61. epoch Time dateToEpoch amp tsl MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 573 CHAPTER 6 Libraries mikroC PRO for AVR Time_epochToDate Prototype void Time epochToDate long e TimeStruct ts Converts the unix time to time and date Parameters Description e unix time seconds since unix epoch ts time and date structure for storing conversion output include timelib h TimeStruct ts2 long epoch what date is epoch 1234567890 epoch 1234567890 Time epochToDate epoch amp ts2 574 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Time_dateDiff Prototype long Time dateDiff TimeStruct tl TimeStruct t2 Returns Time difference in seconds as a signed long This function compares two dates and returns time difference in seconds as a signed long Result is positive if 1 is before t2 result is null if c1 is the same as c2 and result is negative if c1 is after t2 Parameters Description t1 time and date structure the first comparison parameter t2 time and date structure the second comparison parameter Note This function is implemented as macro in the timelib h header file which can be found in the mikroC PRO for AVR Time Library Demo example folder include timelib h TimeStruct sl tes long QYft s how many seconds between these two dat
62. t HHHHBHE 23 444444 lt lt 4 383223228 m5030 4 Cages PiniMooeiektronh dira PRO ter AM of od Crag en Fes iPhoceiektrord PRO AL 555 ane 7 LOG SADEGA 45 lt OIL Hold ACC gt The Code Editor features adjustable Syntax Highlighting Code Folding Code Assistant Parameters Assistant Auto Correct for common typos and Code Tem plates Auto Complete The Code Explorer with Keyboard shortcut browser and Quick Help browser is at your disposal for easier project management The Project Manager alows multiple project management General project settings can be made in the Project Settings window Library manager enables simple handling libraries being used in a project The Error Window displays all errors detected during compiling and linking The source level Software Simulator lets you debug executable logic step by step by watching the program flow The New Project Wizard is a fast reliable and easy way to create a project Help files are syntax and context sensitive 12 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment Like in any modern Windows application you may customize the layout of mikroC PRO for AVR to suit your needs best Spell checker underlines identifiers which are unknown to the project In this way it helps the programmer to spot potential problems
63. 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 Invert the dot in the upper left corner Glcd Dot 0 0 2 288 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Glcd Line void Glcd Line int x start int y start int x end int y end unsigned short color Nothing 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 BeseHpnoh 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 Requires Glcd needs to be initialized Glcd needs to be initialized see Glod Initrouine Glcd needs to be initialized see Glod Initrouine routine pe Draw a line between dots 0 0 and 20 30 Gled Lnine 0 0 20 30 1 Glcd V Line void Glcd V Line unsigned short y start unsigned short y end unsigned short x pos unsigned short color Draws a vertical line on Glcd Parameters y start y coordinate of the line start Valid values 0 63 Description y end y coordinate of the line end Valid values
64. 127 y upper left y coordinate of the upper left rectangle corner Valid values 0 63 x bottom right X coordinate of the lower right rectangle corner Valid values 0 127 y bottom right y coordinate of the lower right rectangle corner Valid values 0 63 color color parameter Valid values 0 2 Description The parameter color determines the color of the rectangle border 0 white 1 black and 2 inverts each dot Requires Glcd needs to be initialized see Glcd Init routine Draw a rectangle between dots 5 5 and 40 40 Glcd Rectangle 5 5 40 40 1 290 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Glcd Box void Glcd Box unsigned short x upper left unsigned short Prototype y upper left unsigned short x bottom right unsigned short y bottom right unsigned short color 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 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 O white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd Init routine
65. 179 67 T6963C WHITE 526 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR CHAPTER 6 Libraries Draw a cross T6963C line 0 0 239 127 T6963C WHITE T6963C line 0 127 239 0 T6963C WHITE Draw solid boxes af T6963C box 0 0 239 8 T6963C WHITE T6963C box 0 119 239 127 T6963C WHITE Draw circles ay T6963C circle 120 64 10 T6963C WHITE T6963C circle 120 64 30 T6963C WHITE T6963C circle 120 64 50 T6963C WHITE T6963C circle 120 64 70 T6963C WHITE T6963C circle 120 64 90 T6963C WHITE T6963C circle 120 64 110 T6963C WHITE T6963C circle 120 64 130 T6963C WHITE T6963C sprite 76 4 einstein 88 119 Draw a sprite T6963C setGrPanel 1 T6963C image mikrol f r P Select other graphic panel 240x128 bmp Endless loop If PBO is pressed display only graphic panel if PINBO T6963C_text 0 Delay ms 300 If PB1 is pressed O and graphic panel oy else if 1 1 panel amp 1 1 T6963C graphics 1 toggle the display between graphic panel T6963C displayGrPanel panel Delay ms 300 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 527 CHAPTER 6 PB2 is pressed wa else if PINB2 T69
66. 22 Back Next gt 78 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment Step Four Add project file to the project if they are avaiable at this point You can always add project files later using Project Manager New Project Wizard Step 4 5 Add project files if they are available at this point You can always add project files later using the Project Manager in IDE Add File To Project C avr_pro c math C_math c FileName C avr_pro C math C_math c Remove Remove All Step Five Click Finish button to create your New Project New Project Wizard Step 5 5 You have successfully created a new project Click Finish to save the changes and to close the wizard D Back 1 Emish Cancel Related topics Project Manager Project Settings MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 79 CHAPTER 2 Environment mikroC PRO for AVR CUSTOMIZING PROJECTS Edit Project You can change basic project settings in the Project Settings window You can change chip and oscillator frequency Any change in the Project Setting Window affects currently active project only so in case more than one project is open you have to ensure that exactly the desired project is set as active one in the Project Manager Managing Project Group mikroC PRO for AVR IDE provides covenient option which enables seve
67. 28 760 write pointer EwRPT location Description Parameters ptr RAM buffer containing bytes to be written into zxc28760 RAM n humber of bytes to be written Ethernet module has to be initialized See SPI Ethernet Init char buffer mikroElektronika SPI Ethernet putBytes buffer 16 put an RAM array into ENC28J60 buffer MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 439 CHAPTER 6 Libraries mikroC PRO for AVR SPI_Ethernet_putConstBytes void SPI Ethernet putConstBytes const unsigned char Prototype unsigned char n This is MAC module routine It stores requested number of const bytes into ENC28360 RAM starting from current zxc28360 write pointer EWRPT location Description Parameters ptr const buffer containing bytes to be written into ENc28760 RAM n number of bytes to be written Ethernet module has to be initialized See Ethernet Init const char buffer mikroElektronika SPI Ethernet putConstBytes buffer 16 put a const array into ENC28J60 buffer SPI_Ethernet_putString Prototype unsigned int SPI Ethernet putString unsigned char ptr Returns Number of bytes written into 28760 RAM This is MAC module routine It stores whole string excluding null termination into ENC28360 RAM starting from current Nc28760 write pointer EwRPT location Descripti
68. 35 break kp 48 Store key code in kp variable Store key code in kp variable transform key to it s ASCII value Jo Wes Uncomment this block 9 ng C 302 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR case 1 kp 49 for keypad4x4 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 57 case 12 kp 67 case 13 kp 42 case 14 kp 48 case 15 kp 35 case 16 kp 68 if kp oldstate cnt 1 oldstate kp else CDI Lcd Chr 1 10 kp if cnt 255 cnt 0 Hed Out 2 10 T WordToStr cnt txt Lcd Out 2 10 txt while 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 Libraries break 1 Uncomment this block break 2 break 3 break A break 4 break 5 break 6 break B break 7 break 8 break 9 break C break break 0 break break D Pressed key differs from previous Pressed key is same as previous Print key ASCII value on LCD If counter varialble overflow Transform counter value to string Display counter value on LCD 303 CHAPTER 6 Libraries mikroC PRO for AVR HW Connection 9LVO3INLV a
69. Examples for AVR MCUs with module on other ports can be found in your mikroC for AVR installation folder subfolder Examples Library Routines TWI Init TWI Busy TWI Start TWI Stop TWI Read TWI Write TWI Status TWI Close TWI Init Prototype TWI Init unsigned long clock Initializes TWI with desired clock refer to device data sheet for correct values in respect with Fosc Needs to be called before using other functions of TWI Library Description You don t need to configure ports manually for using the module library will take care of the initialization Library requires MSSP module on PORTB or PORTC Example fincas SY 530 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries TWI_Busy Returns Returns 0 if TWI start sequnce is finished 1 if TWI start sequnce is not finished Signalizes the status of TWI bus TWI must be before using this function See TWI_Init 2 TWI Start itis ne oror umi TWI_Read Returns Returns one byte from the slave Reads one byte from the slave and sends not acknowledge signal if parameter ack is 0 otherwise it sends acknowledge Description TWI must be configured before using this function See TWI Init Requires Also START signal needs to be issued in order to use this function See TWI Start Re
70. FUNCTION DEFINITION Function definition consists of its declaration and function body The function body is technically a block a sequence of local definitions and statements enclosed within braces All variables declared within function body are local to the func tion i e they have function scope 188 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference 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 in func tions of the void type cannot a parameter in fact the return statement can be omitted altogether if it is the last statement in the function body Here is a sample function definition function max returns greater one of its 2 arguments int max int x int return gt x y Here is a sample function which depends on side effects rather than return value function converts Descartes coordinates x y to polar r fi include math h void polar double x double y double r double fi ep cosqret x x oy yj xfi 0 amp amp y 0 0 atan2 y x return this line can be omitted Functions reentrancy Functions reentrancy is allowed Remember that the AVR has stack and memory limitations which can varies greatly betwe
71. MODE em N 510 2554 Duty Ratio 7 7 Description Y tewm 2tewm 3towm 4towm Stew 6towm 7 towne 1 f Non Inverted Inverted 1 1 1 1 variable represents the prescaler factor 1 8 64 256 1024 Some modules also support 32 and 128 prescaler value but for this you will need to check the datasheet for the desired MCU MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 377 CHAPTER 6 Libraries Description mikroC PRO for AVR i o Town 256 74 3tew teum Ote 7 Non Inverted Inverted The N variable represents the prescaler factor 1 8 64 256 or 1024 Some modules also support 32 and 128 prescaler value but for this you will need to check the datasheet for the desired MCU PWMIA1 Init must be called before using other functions from PWM Library You need a CMO on the given MCU that supports PWM Before calling this routine you must set the output pin for the PWM according to the datasheet DDRD 7 1 set PORTD pin 7 as output for the PWM1 This code oxample is for ATmega16 second PWM module for different MCU please consult datasheet for the correct pinout of the PWM module or modules Initialize PWM module PWM1 Init PWM1 FAST MODE PWM1 PR ER 8 NON INVE 127 378 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLU
72. Note Some AVR MCU s have alternative SPI ports which SPI signals can be redirected to by setting or clearing SPIPS SPI Pin Select bit of the MCUCR register Please consult the appro priate datasheet Library Routines SPI Init SPI1 Init Advanced SPI1 Read SPI1 Write SPI Init Prototype void SPI1 Init Nothing This routine configures and enables SPI module with the following settings master mode EN 8 bit data transfer Description most significant bit sent first serial clock low when idle data sampled on leading edge serial clock fosc 4 Requires MCU must have SPI module Example Initialize the SPI1 module with default settings SPIL Init 426 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI1_Init_Advanced Prototype void SPI1 Init Advanced char mode char fcy div char clock and edge Configures and initializes SPI SPI1 Init Advanced or SPI1 Init needs to be called before using other functions of SPI Library Parameters mode fcy div and clock and edge determine the work mode for SPI and can have the following values ask Description Predefined brary const SPI mode constants Clock rate select constants Sck Fosc 4 Master mode SPI FCY DIV4 Sck Fosc 16 Master mode SPI DIV16 Sck Fosc 64 Master mode SPI FCY DIV64 Sck Fosc 128 Master mode SPI FCY DIV128 Description
73. Redo last change Cut selected text to clipboard Copy selected text to clipboard Paste text from clipboard MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 21 CHAPTER 2 Environment mikroC PRO for AVR Advanced Edit Toolbar 20 91 5 ud Advanced Edit Toolbar comes with following options Icon Description Comment selected code or put single line comment if there is no selection Uncomment selected code or remove single line comment if there is no selection Select text from starting delimiter to ending delimiter Go to ending delimiter ENDI gt Go to line ae Indent selected code lines Outdent selected code lines Ld Generate HTML code suitable for publishing current source code on the web Find Replace Toolbar PAP wR Find Replace Toolbar is a standard toolbar with following options Icon Description Find text in current editor Find next occurence 2 Find previous occurence Replace text Find text in files 22 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment Project Toolbar BRYSIA Project Toolbar comes with following options Icon Description Open new project wizard wizard ghe Open Project Save Project
74. Use relational operators to test equality or inequality of expressions If an expres sion evaluates to be true it returns 1 otherwise it returns 0 All relational operators associate from left to right Relational Operators Overview e greater than or equal less than or equal Relational Operators in Expressions Precedence of arithmetic and relational operators is designated in such a way to allow complex expressions without parentheses to have expected meaning a 5 gt c 1 0 e gt a 5 gt 1 0 e Do not forget that relational operators return either O or 1 Consider the following examples ok gt 7 returns 0 10 lt 20 returns 1 this can be tricky 8 13 gt 5 returns 0 as 8 13 gt 5 8 0 14 gt 5 lt 3 returns 1 14 gt 5 3 1 23 9 1 a lt b lt 5 returns 1 as a lt b lt 5 2 0 1 lt 5 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 197 CHAPTER 5 Language Reference mikroC PRO for AVR 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 if both bits are 1 otherwise returns 0
75. Valid values 0 7 Toshiba GLCD module needs to be initialized See the T6963C Init routine Eumpe T6963C Graphics Enable disable graphic displaying Parameters Description n on off parameter Valid values o disable graphic displaying and 1 enable graphic displaying Toshiba GLCD module needs to be initialized See the T6963C Init routine enable graphic displaying T6963C Graphics 1 T6963C Text Enable disable text displaying Description Parameters n on off parameter Valid values o disable text displaying and 1 enable text displaying Toshiba GLCD module needs to be initialized See the T6963C Init routine enable text displaying T6963C Text 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 523 CHAPTER 6 Libraries mikroC PRO for AVR T6963C_Cursor Prototype void T6963C Cursor char n Nothing Set cursor on off Description Parameters n on off parameter Valid values o set cursor off and 1 set cursor on Toshiba GLCD module needs to be initialized See the T6963C Init routine set cursor on T6963C Cursor 1 T6963C Cursor Blink Prototype void T6963C Cursor Blink char n Nothing Enable disable cursor blinking Description Parameters n on off parameter Valid values 0 disable cursor blinking and 1 enable cursor blinking Toshiba GLCD module needs to be initialized See the T
76. bitwise inclusive OR compares pairs of bits and returns 1 if either or both bits are 1 otherwise returns 0 bitwise exclusive OR XOR compares pairs of bits and returns 1 if the bits are complementary other wise returns 0 bitwise complement unary inverts each bit bitwise shift left moves the bits to the left discards the far left bit and assigns 0 to the far right bit bitwise shift right moves the bits to the right dis cards the far right bit and if unsigned assigns 0 to the far left bit otherwise sign extends Bitwise operators and perform logical operations on the appropriate pairs of bits of their operands Operator complements each bit of its operand For example 0x1234 amp 0x5678 equals 0x1230 because 0x1234 0001 0010 0011 0100 0x5678 0101 0110 0111 1000 198 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference amp 0001 0010 0011 0000 that is 0x1230 Similarly 0x1234 0x5678 equals 0x567C 0x1234 0x5678 equals 0x444C 0x1234 equals OxEDCB Note Operator amp 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 po
77. char txt 6 WordToStr t txt txt is 437 two blanks here IntToStr Prototype void IntToStr int input char output Converts input signed integer number to a string The output string has fixed width of 7 characters including null character at the end string termination The output string is right justified and the remaining positions on the left if any are filled with blanks Description Parameters input signed integer number to be converted output destination string Requires Destination string should be at least 7 characters in length int 1 4220 char txt 7 IntToStr j txt txt is 4220 one blank here MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 563 CHAPTER 6 Libraries mikroC PRO for AVR LongToStr Prototype void LongToStr long input char output Converts input signed long integer number to a string The output string has fixed width of 12 characters including null character at the end string termina tion The output string is right justified and the remaining positions on the left if any are filled with blanks Description Parameters input signed long integer number to be converted output destination string Destination string should be at least 12 characters in length long jj 3700000 char txt 12 LongToStr jj txt xe ig T 3700000 three blanks here LongWordToStr Prototype void LongWordToStr
78. consult the appropriate MCU datasheet for details about available EEPROM size and constrains Library Routines EEPROM_Read EEPROM_Write EEPROM_Read Prototype unsigned short EEPROM Read unsigned int address Byte from the specified address Reads data from specified address Description Parameters address address of the EEPROM memory location to be read Requires Nothing unsigned int address 2 unsigned short temp temp EEPROM Read address MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 275 CHAPTER 6 Libraries mikroC PRO for AVR EEPROM_Write Prototype void EEPROM Write unsigned address unsigned short dData Nothing Writes wrdata to specified address Parameters Description address address of the EEPROM memory location to be written wrdata data to be written Note Specified memory location will be erased before writing starts Requires Nothing unsigned address 0x732 unsigned short dData 0x55 EEPROM Write address dData 276 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Library Example This example demonstrates using the EEPROM Library with ATMEGA16 MCU First some data is written to EEPROM in byte and block mode then the data is read from the same locations and displayed on PORTA PORTB and PORTC char dat
79. double atan double f Function computes the arc tangent of parameter f that is the value whose tan Deperpten gent is f The return value is in radians between 2 2 inclusive atan2 Prototype double atan2 double y double x This is the two argument arc tangent function It is similar to computing the arc tangent of y x except that the signs of both arguments are used to determine the quadrant of the result and x is permitted to be zero The return value is in radians between and inclusive Description ceil Prototype Function returns value of parameter x rounded up to the next whole number cos Prototype Function returns the cosine of in radians The return value is from 1 to 1 546 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries cosh Prototype double cosh double x Function returns the hyperbolic cosine of x defined mathematically as e e X 2 If the value of x is too large if overflow occurs the function fails eval_poly Prototype static double eval poly double x const double code d int n Function Calculates polynom for number x with coefficients stored in d Description degree n exp Prototype double exp double x 598 Function returns the value of e the base of natural logarithms raised to the Description power x i e e fabs P
80. down amp amp keydata 13 Enter UART1 Write r send carriage return to usart terminal UART1_Write n uncomment this line if usart terminal also expects line feed for new line transition else if down amp amp special amp amp keydata UART1 Write keydata Delay ms 10 debounce while 1 370 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries HW Connection VCC VCC 52 GND OSCILLATOR Example of PS2 keyboard connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 371 CHAPTER 6 Libraries mikroC PRO for AVR PWM LIBRARY CMO module is available with a number of AVR MCUs mikroC PRO for AVR pro vides library which simplifies using PWM HW Module Note For better understanding of PWM module it would be best to start with the example provided in Examples folder of our mikroC PRO for AVR compiler When you select a MCU mikroC PRO for AVR automaticaly loads the correct PWM library or libraries which can be verified by looking at the Library Manager PWM library handles and initializes the PWM module on the given AVR MCU but it is up to user to set the correct pins as PWM output this topic will be covered later in this section mikroC PRO for AVR does not support enhanced PWM modules
81. expected but 551 found Array element cannot be function Function cannot return array Inconsistent storage class Inconsistent type s tag redefined 251 Illegal typecast s s s is not valid identifier Invalid statement Constant expression required Internal error s Too many actual parameters Not enough parameters Invalid expression Identifier expected but 5 found Operator 51 is not applicable to these operands 55 Assigning to non lvalue 251 Cannot cast 5 to s Cannot assign s to s Lvalue required Pointer required Argument is out of range Undeclared identifier 5 expression Too many initializers Cannot establish this baud rate at 2s MHz clock Stack overflow Invalid operator Expected variable but constant 2 1 found Expected constant but 551 found s cannot be used outside a loop Unknown type 5s Variable 51 is redeclared Undeclared identifier 251 Output limit has raised 2K words Ves has already been declared 251 Type mismatch expected s but ss found File s not found 55 There is not enough RAM space for all variables There is not enough ROM space Invalid type in Array MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 87 CHAPTER 2 Environment mikroC PRO for AVR Division by zero Incompatible types s
82. the expression is evaluated These standard conversions include promotions of lower types to higher types in the interests of accuracy and consistency Assigning a signed character object such as a variable to an integral object results in automatic sign extension Objects of type signed char always use sign extension objects of type unsigned char always has its high byte set to zero when converted to int Converting a longer integral type to a shorter type truncates the higher order bits and leaves low order bits unchanged Converting a shorter integral type to a longer type either sign extends or zero fills the extra bits of the new value depending on whether the shorter type is signed or unsigned respectively Note Conversion of floating point data into integral value in assignments or via explicit typecast produces correct results only if the float value does not exceed the scope of destination integral type In details Here are the steps the mikroC PRO for AVR uses to convert the operands in an arithmetic expression First any small integral types are converted according to the following rules 1 char converts to int 2 signed char converts to int with the same value 3 short converts to int with the same value sign extended 4 unsigned short converts to int with the same value zero filled 5 enum converts to int with the same value MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORL
83. the user should call this routine once again or Man_Synchro routine to enable synchronization Global variables MANRXPIN Receive line MANRXPIN Direction Direction of the receive pin must be defined before using this function Initialize Receiver sbit MANRXPIN at PORTB BO sbit MANRXPIN Direction at DDRB BO Man Receive Init MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 315 CHAPTER 6 Libraries mikroC PRO for AVR Man_Receive Prototype unsigned char Man Receive unsigned char error Returns A byte read from the incoming signal The function extracts one byte from incoming signal Parameters Description error error flag If signal format does not match the expected the error flag will be set to non zero To use this function the user must prepare the MCU for receiving See Requires Man_Receive_Init 0 unsigned char data 0 error data Man Receive amp if error error handling Man Send Init Prototype The function configures Transmitter pin Global variables MANTXPIN Transmit line MANTXPIN Direction Direction of the transmit pin must be defined before using this function Initialize Transmitter sbit MANTXPIN at 1 sbit MANTXPIN Direction at DDRB B1 Man Send Init 316 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC P
84. unsigned long input char output Converts input unsigned long integer number to a string The output string has fixed width of 11 characters including null character at the end string termina tion The output string is right justified and the remaining positions on the left if any are filled with blanks Description Parameters input unsigned long integer number to be converted output destination string Requires Destination string should be at least 11 characters in length unsigned long jj 3700000 char txt 11 LongTOStr j txt Z4 EX 3700000 three blanks here 564 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries FloatToStr Prototype unsigned char FloatToStr float fnum unsigned char str 3 if input number is NaN 2 if input number is INF 1 if input number is INF 0 if conversion was successful Converts a floating point number to a string Parameters fnum floating point number to be converted Description str 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 Requires Destination string should be at least 14 characters in length float ffl 374 2 float ff2 123 456789 float ff3 0 000001234 char txt 15 FloatToStrittil txt PloatToStr ft2 txt 7
85. void SPI T6963C Cursor Blink char n Nothing Enable disable cursor blinking Parameters Description n cursor blinking enable disable parameter Valid values o disable cursor blinking and 1 enable cursor blinking Toshiba Glcd module needs to be initialized See SPI T6963C Config routine enable cursor blinking SPI T6963C Cursor Blink l 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 EasyAVR5 board and ATmega16 include SPIT6963C h bitmap pictures stored in ROM sy extern const code char extern const code char einstein Port Expander module connections sbit SPExpanderRST at PORTB BO sbit SPExpanderCS at PORTB B1 sbit SPExpanderRST Direction at DDRB B0 sbit SPExpanderCS Direction at DDRB B1 End Port Expander module connections void main char txtl EINSTEIN WOULD HAVE LIKED mE char txt Glcd LIBRARY DEMO WELCOME 500 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries unsigned char panel current panel unsigned int general purpose register unsigned char curs cursor visibility unsigned int cposx cposy cursor x y position DDRA 0x00 configure PORTA as input
86. 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 293 CHAPTER 6 Libraries mikroC PRO for AVR Glcd_Write_Text void Glcd Write Text char text unsigned short x pos unsigned Prototype short num unsigned short color 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 Description values 0 7 color color parameter Valid values 0 2 The parameter color determines the color of the text O white 1 black and 2 inverts each dot Note For x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized see Glcd Init routine Use Glcd Set Font to specify the font for display if no font is specified then default 5x8 font supplied with the library will be used Write text Hello world on the position 10 inside the page 25 Glcd Write Text Hello world 294 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Glcd Image Prototype void Glcd Image code const unsigned short image CHAPTER 6 Libraries Nothing Displays bitmap on Glcd Parameters Description image image to be displayed Bitmap array must be located in code memory Use the mikroC PRO for AVR integrated Glcd Bitmap Editor to convert image to a constant array suitable for
87. 12C Init Configures the software 2 module Global variables Requires must be defined before using this function Software I2C connections sbit sbit sbit sbit sbit End Software I2C connections Soft I2C Init A12C Init Soft I2C Scl Soft I C clock line Soft I2C Sda Soft I C data line Soft I2C Scl Pin Direction Direction of the Soft I C clock pin Soft I2C Sda Pin Direction Direction of the Soft I C data pin Soft I2C Scl Output at PORTC BO Soft I2C Sda Output at 1 Soft I2C Scl Input at PINC B0 Soft I2C Sda Input at Soft I2C Scl Direction at DDRC B0 Soft I2C Sda Direction at DDRC B1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 403 CHAPTER 6 Libraries mikroC PRO for AVR Soft I2C Start Prototipe Determines if the 12C bus is free and issues START signal Software 12C must be configured before using this function See Soft I2C Init routine Issue START signal Soft I2C Start Soft I2C Read Prototype unsigned short Soft I2C Read unsigned int ack Returns One byte from the Slave Reads one byte from the slave Parameters Description ack acknowledge signal parameter If the ack 0 not acknowledge signal will be sent after reading otherwise the acknowledge signal will be sent Soft C must be configured before using this function See Soft I2C Init routine Requires Also START signal needs to
88. 2 Write string 32 Change font Write string 5 2 Write string 5 7 32 Change font 6 2 Write string 7 2 Write string 467 CHAPTER 6 Libraries mikroC PRO for AVR HW Connection o Left side Right side X puis 23517 0 ri 8 Do cemo cpa7 28 Pt Jn pet cras 02 3 26 RST GPB2 eras 95 4H EE n DA 5 24 RW GPB4 Ee GPB5 craz 22 8S D6 7H opa 1 2 cs2 p aly 86 21 csi oo GPB7 D E 20 6 1 VDD naj Ho 1 9 gt PB 1 1114 VSS 18 0 5 RESET L AN 7124 A2 eo 5 13 16 si a H PB 6 141 15 so Ao pe Vee Contrast Adjustment s vec p SPI Glcd HW connection 468 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI LCD LIBRARY The mikroC PRO for AVR provides a library for communication with Lcd with HD44780 compliant controllers in 4 bit mode via SPI interface For creating a custom set of Lcd characters use Lcd Custom Character Tool Note The library uses the SPI module for communi
89. 32 ii Data buffer loop variable void main DDRA OxFF set PORTA as output DDRB OxFF set PORTB as output DDRC OxFF set PORTC as output for 31 ii ii ii 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 0x100 Delay_ms 1000 Blink PORTA and PORTB diodes PORTA OxFF ZW to indicate reading start PORTB OxFF Delay ms 1000 PORTA 0x00 PORTB 0x00 Delay ms 1000 PORTA EEPROM Read 2 Read data from address 2 and display it on PORTA PORTB EEPROM Read 0x732 Read data from address 0x732 and display it on PORTB Delay ms 1000 for ii 0 ii lt 32 Read 32 bytes block from address 0x100 PORTC EEPROM 0 100 11 and display data on PORTC Delay ms 100 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 277 CHAPTER 6 Libraries mikroC PRO for AVR FLASH MEMORY LIBRARY This library provides routines for accessing microcontroller Flash memory Note that prototypes differ for MCU to MCU due to the amount of Flash memory Note Due to the AVR family flash specifics flash library is MCU dependent Since some AVR MCU s have more or less than 64kb of Flash memory prototypes m
90. 4 MikroElektronika SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD waking ib sie ple Develop your applications quickly and easily with the world s most intuitive mikroC PRO for AVR Microcontrollers e e e ejje 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 PRO for AVR makes a fast and reliable tool which can satisfy needs of experienced engineers and beginners alike mikroC PRO for AVR December 2008 Reader s note DISCLAIMER mikroC PRO for AVR 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 without 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 prohibited HIGH RISK ACTIVITIES The mikroC PRO for AVR compiler is not fault tolerant and is not designed manufactured or intended for use or resale as on line control equipment in hazardous environments requir ing fail safe performanc
91. 5 m SPI Lcd8 HW connection 482 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI T6963C GRAPHIC LCD LIBRARY The mikroC PRO for AVR provides a library for working with Glcds based on TOSHIBA T6963C controller via SPI interface The Toshiba T6963C is a very popu lar Lcd controller for the use in small graphics modules It is capable of controlling displays with a resolution up to 240x128 Because of its low power and small out line it is most suitable for mobile applications such as PDAs MP3 players or mobile measurement equipment Although this controller is small it has a capability of dis playing and merging text and graphics and it manages all interfacing signals to the displays Row and Column 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 External dependencies of SPI T6963C Graphic Lcd Library The implementat
92. 90 Software Simulator Overview 91 Watch Window 0 00 cee RR RH n 91 Stopwatch Window 93 RAM WindOW 2 2 4 94 Software Simulator Options 95 Creating New Library 4 96 Multiple Library Versions 96 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD VII Table of Contents mikroC PRO for AVR CHAPTER 3 Mec 98 ANSI Standard Issues 98 Divergence from the ANI C Standard 98 Predefined Globals and Constants 99 Predefined project level defines 99 Accessing Individual Bits 100 Accessing Individual Bits Of Variables 100 cp ve pre en AE oe Se AE De 100 cux Dex Ga UR ks nandi eo s Ud e os 101 T 102 Function Calls from Interrupt 102 Linker Directives 104 Directive absolute 104 Directive Org DP 104 Direc ve orgal ik ee cae REED ea CA ee bx Ya 105 Indirect Function Calls
93. B1 End Soft UART connections Initialize Software UART communication at 9600 Soft UART Init 9600 0 416 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Soft_UART_Read Prototype Soft UART Read char error Byte received via UART The function receives a byte via software UART This is a blocking function call waits for start bit Programmer can unblock it by calling Soft UART Break routine Description Parameters error Error flag Error code is returned through this variable 0 no error 1 stop bit error 255 user abort Soft UART Break called Software UART must be initialized before using this function See the Soft UART Init routine char data error wait until data is received do data Soft UART Read amp error while error Now we can work with data if data 1224 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 417 CHAPTER 6 Libraries mikroC PRO for AVR Soft_UART_Write Prototype void Soft UART Write char udata This routine sends one byte via the Software UART bus Description Parameters udata data to be sent Software UART must be initialized before using this function See the Soft UART Init routine Be aware that during transmission software UART is incapable of receiving data data transfer protocol must be set in such a way to prevent
94. BLOCK_SIZE is not currently defined the middle line is invoked to define it MACROS WITH PARAMETERS The following syntax is used to define a macro with parameters define macro identifier arg list token sequence Note that there can be no whitespace between macro identifier and The optional arg list is a sequence of identifiers separated by commas like the argu 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 macro identifier actual arg list in the subsequent source code The 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 in 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 em
95. Boot Record i e there is only one logical partition and no MBRs the library works with entire card as a single partition For more information on MBR physical and logical drives primary secondary partitions and partition tables please consult other resources e g Wikipedia and similar Note Before writing operation make sure not to overwrite boot or FAT sector as it could make your card on PC or digital camera unreadable Drive mapping tools such as Winhex can be of great assistance MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 251 CHAPTER 6 Libraries mikroC PRO for AVR External dependencies of Compact Flash Library The following variables must be defined in all projects using Compact Flash Library Description Compact Flash Data Port extern sfr char CF Data Port extern sfr char CF Data Port Direction extern sfr sbit CF R Direction of the Com pact Flash Data Port i El extern sfr sbit CF extern sfr sbit CF 2 Direction of the Ready pin Direction of the Write Enable pin Direction of the Output Enable pin Direction of the Chip Detect pin extern sfr sbit CF RDY direction extern sfr sbit CF WE direction extern sfr sbit CF OE direction extern sfr sbit CF CD1 direction extern sfr sbit CF CE1 direction Direction of the Chip Enable pin extern sfr sbit Direction of the Address CF A2 direction 2 pin Output Enab
96. Click the window you want to keep visible to give it focus Click the Pushpin Icon jon the title bar of the window kotea ey 4 tes ey 7 Sources SecondProject c E Header Files Binaries 73 Project level defines Image Files 7 Output Files E Other Files 4 asusausauiunauu nus ad When auto hidden window loses focus it automatically slides back to its tab the edge of the IDE While a window is auto hidden its name and icon are visible on a tab at the edge of the IDE To display an auto hidden window move your point er over the tab The window slides back into view and is ready for use MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 39 CHAPTER 2 Environment mikroC PRO for AVR ADVANCED CODE EDITOR The Code Editor is advanced text editor fashioned to satisfy needs of professionals General code editing is the same as working with any standard text editor including familiar Copy Paste and Undo actions common for Windows environment Advanced Editor Features Adjustable Syntax Highlighting Code Assistant Code Folding Parameter Assistant Code Templates Auto Complete Auto Correct for common typos Spell Checker Bookmarks and Goto Line Comment Uncomment You can configure the Syntax Highlighting Code Templates and Auto Correct from the Editor Settings dialog To access the Settings click To
97. Code Optimization Memory Type Specifiers 97 CHAPTER 3 Specifics mikroC PRO for AVR Notes Directive absolute in Rx memory space guarantees only that defined variable will be overlapped with the given memory address Addresses of all registers are RAM Space addresses RAM Space is con tinuous region of RAM memory including all AVR RAM memory spaces RAM space Rx Space IO Space SRAM Space When using instruc tions dedicated to IO Space in asm blocks IO registers should be accessed by their RAM Space addresses Refer to AVR memory organization for details on RAM Space addresses Currently Boot Loader section of the flash memory is not supported by the compiler Rx space not used by the compiler may be used for user variables So the size of the available Rx space is not fixed because it depends on the memory consumtion of the project itself Compiler uses not less than 7 Rx registers Literal strings are stored according to the destination Flash or RAM If stored in RAM they are linked as a global and always exist by default There is an option for storing literal string on the function frame Constants may be stored only in the first 64kb of Flash memory Available RAM memory is divided on static and dynamic link Static link grows upwards from lower to higher addresses Dynamic link grows downwards from higher to lower addresses In case of intensive cross callings recursions etc it is not gua
98. 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 ATE du i Xs an int int pi pi is a pointer to int uninitial ized int const cp amp i cp is a constant pointer to int const int ci 7 ci is a constant int const int pci pci is a pointer to constant int const int const cpc amp ci cpc is a constant pointer to a 7 constant int The following assignments are legal i ci Assign const int to int gu Assign const int to object pointed at by a const pointer Increment a pointer to const pci cpc Assign a const pointer to a const to a 2 pointer to const The following assignments are illegal ci 0 NO cannot assign to a const int Giss NO cannot change a const int pci 3 NO cannot assign to an object pointed at by pointer to const cp amp ci NO cannot assign to a const pointer Er even if value would be unchanged NO cannot change const pointer pi pci NO if this assignment were allowed EL you would be able to assign to pci 72 a const value assigning to pi Similar rules are applayed to the volatile modifier Note that both const and volatile can appear as modifiers to the same identifier
99. DDRD B4 sbit LCD D5 Direction at DDRD B5 sbit LCD D6 Direction at DDRD B6 sbit LCD D7 Direction at DDRD B7 End LCD module connections OneWire pinout sbit OW Bit Write at PORTB B2 sbit OW Bit Read at PINB B2 sbit OW Bit Direction at DDRB B2 end OneWire definition Set TEMP RESOLUTION to the corresponding resolution of used DS18x20 sensor 18820 9 default setting can be 9 10 11 or 12 18B20 12 const unsigned short TEMP RESOLUTION 9 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 temperature is negative if temp2write amp 0x8000 text 0 temp2write temp2write 1 350 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries extract temp whole temp whole temp2write gt gt RES SHIFT convert temp whole to characters if temp whole 100 text 0 temp whole 100 48 text 1 temp 1 10 10 48 Extract tens digit text 2 temp whole 10 48 Extract ones digit extract temp fraction and convert it to unsigned int temp fraction temp2write lt lt 4 RES SHIFT temp fraction amp 0 000 temp fraction 625 convert temp fraction to characters text 4 temp fraction
100. Description Requires mikroC PRO for AVR Parameters input byte to be converted output destination string Destination string should be at least 4 characters in length unsigned short t 24 char txt 4 ByteToStr t txt txt is 24 one blank here void ShortToStr short input char output Nothing 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 out put 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 short t 24 char txt 5 ShortToStr t txt txt is 24 one blank here 562 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries WordToStr Prototype void WordToStr unsigned input char output Converts input word to a string The output string has fixed width of 6 characters including null character at the end string termination The output string is right justified and the remaining positions on the left if any are filled with blanks Description Parameters input word to be converted output destination string Destination string should be at least 6 characters in length unsigned t 437
101. FIRST ROW Move cursor to the 1st row while 1 Wait for the start byte temp Man Receive amp error Attempt byte receive if temp 0x0B Start byte see Transmitter example break We got the starting sequence if error Exit so we do not loop forever break MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 319 CHAPTER 6 Libraries mikroC PRO for AVR do temp Man Receive amp error Attempt byte receive if error If error occured hod Chr CESI Write question mark on LCD ErrorCount t Update error counter if ErrorCount gt 20 In case of multiple errors temp Man Synchro Try to synchronize again Man Receive Init Alternative try to Initialize Receiver again ErrorCount 0 Reset error counter else No error occured if temp OxOE If End byte was received see Transmitter example Lcd Chr CP temp do not write received byte on LCD Delay ms 25 while temp OxOE If 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 PORTB BO sbit MANRXPIN Direction at DDRB BO sbit MANTXPIN at PORTB B1 sbit MANTXPIN Direction at DDRB Bl End Manchester module connections char index character char 51 mi
102. FOR EMBEDDED WORLD mikroC PRO for AVR Table of Contents SPI Gled V Line sca egies eae 459 SPI Glcd H Bine cente ie pem ine ep ete ee 459 SPI Gled Rectangle 460 SPI Gled oii t tide dade 460 Glcd Circle gt each ged oe REI ed ERR ERE 461 SPL Gled Set Font i2 e Rex x ew CR a 462 SPI Glcd Write 463 SPI Write 464 SPI Gled Image 465 Library 465 HW Connection ence bee bebe debebat eh 468 SBI Ecd EIDrany sz nce oc ek baw aos bo REED bans Ca tad ERE 469 External dependencies of SPI Lcd Library 469 Library Routines i eda Meda deeded ents 469 SPL Led Config 3 ae rte x be t e IE IR eee aie eee 470 SPI Led OUl sok e br ae oe OM ae hd eas 471 Led Qut Cp esta jena e 471 SPI bed Chr i iuo bre be b Eee RR ibtd 472 SPI Led Chr Cp ooa Dp ede epa reet 472 SPI bed CMG SEPT RUE PEqudque pud Rt 473 Available Lcd Commands 473 Library 474 HW Connection 2 2 4 44 4 005 RE 475 SPI Lcd8 8 bit interface
103. GLCD module needs to be initialized See the T6963C Init routine Example T6963C Dot x0 yO pcolor 512 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries T6963C_Write_Char void T6963C Write Char unsigned char c unsigned char x unsigned char y unsigned char mode Nothing Writes a char in the current text panel of GLCD at coordinates x y Prototype Parameters c Char to be written x Char position on x axis y Char position on y axis mode mode parameter Valid values T963C ROM MODE OR T6963C ROM MODE XOR T6963C ROM MODE AND and T6963C ROM MODE TEXT Mode parameter explanation Description OR Mode In the OR Mode text and graphics can be displayed and the data is logically OR ed This is the most common way of combin ing text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in the negative mode i e white text on black background AND Mode The text and graphic data shown on display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Toshiba GLCD module needs to be initialized See the T6963C Init routine
104. GOnst continue default do double else enum extern fOr goto ew gef anit long register return short signed sizeof Btruct switch typedef union unsigned void volatile while Also the mikroC PRO for AVR includes a number of predefined identifiers used in libraries You could replace them by your own definitions if you want to develop your own libraries For more information see mikroC PRO for AVR Libraries 136 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference IDENTIFIERS Identifiers are arbitrary names of any length given to functions variables symbolic constants user defined data types and labels All these program elements will be referred to as objects throughout the help don t get confused with the meaning of object in object oriented programming Identifiers can contain the letters a to z and A to Z underscore character _ and digits O to 9 The only restriction is that the first character must be a letter or an underscore Case Sensitivity The mikroC PRO for AVR identifiers are not case sensitive by default so that sum sum and suM represent an equivalent identifier Case sensitivity can be activated or suspended in Output Settings window Even if case sensitivity is turned off Key words remain case sensitive and they must be written in lower
105. Keyboard shortcuts Edit Toolbar Advanced Edit Toolbar MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 19 CHAPTER 2 Environment mikroC PRO for AVR VIEW MENU OPTIONS Toolbars b Debug Windows Routines List Project Settings E Code Explorer Project Manager Ctri F11 Library Manager Bookmarks Messages Macro Editor Windows Debug Windows Show Hide debug windows Show Hide Routine List in active editor Show Hide Project Settings window Show Hide Code Explorer window Project Manager Shift Ctrl F11 Show Hide Project Manager window Show Hide Library Manager window Show Hide Bookmarks window Show Hide Error Messages window Show Hide Macro Editor window Show Window List window 20 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment TOOLBARS File Toolbar 8 9 File Toolbar is a standard toolbar with following options Icon Description 11 Opens new editor window x v Open source file for editing or image file for viewing Save changes for active window io Save changes in all opened windows lu Close current editor o E Close all editors 57 Print Preview Edit Toolbar ae Edit Toolbar is a standard toolbar with following options Icon Description A Undo last change
106. Library Functions 550 C Lm 550 AT Rae 20 550 ALON Pe 551 Civ 551 e PA ees ee ante adh eee 551 ee we ae gees 551 uldiV ursa Wi ah aE ae a 552 seam RR huc PHAR ER I EN RR EE db 552 MAX PP 552 unc P 552 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XX VII Table of Contents mikroC PRO for AVR CMT ge ais a pe 552 SHAN 5 ase oe Poe 552 MOM 553 Div Structures 22250 bite id dda d dg 553 ANSI String Library 554 Library Functions 2 y ERE te AERA ERA 554 iue ced eR E E e RR OR US 555 Missus 555 Aen re Rea A eR RR 555 MEMMOVE a saccus acp eee RO UR IRR e RET 555 memset beber NEED ee ve e pi rede 555 SUCAL 556 556 Strcmp hii aad et 556 Cice E 556 Pc 556 lig PL 557 SUMCDY RP edat debes Blige ick dor debes 557 licec 557 Snem TP 5
107. M Stew M 6tewm 7t w M Description Non Inverted Inverted The N variable represents the prescaler factor 1 8 64 256 or 1024 Some modules also support 32 and 128 prescaler value but for this you will need to check the datasheet for the desired MCU PWM Init must be called before using other functions from PWM Library You need a CMO on the given MCU that supports PWM Before calling this routine you must set the output pin for the PWM according to the datasheet DDRB 3 1 set PORTB pin 3 as output for the PWM This code oxample is for ATmega16 for different MCU please consult datasheet for the correct pinout of the PWM module or modules Initialize PWM module PWM Init PWM FAST MODE ER 8 PWM NON INVE 127 3 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 375 CHAPTER 6 Libraries mikroC PRO for AVR PWM Set Duty Prototype void PWM Set Duty unsigned short duty Changes PWM duty ratio Parameter duty takes values from 0 to 255 where 0 Description is 0 127 is 5096 and 255 is 100 duty ratio Other specific values for duty ratio can be calculated as Percent 255 100 PWM module must to be initialised PWM Init before using Set Duty equines function For example lets set duty ratio to 75 PWM Set Duty 192 PWM Start MCU must have CMO module to use this library PWM Init must be called before using this routi
108. Prototype void Cf Enable void Enables the device Routine needs to be called only if you have disabled the Description device by means of the Cf Disable routine These two routines in conjunction allow you to free occupy data line when working with multiple devices MCU ports must be appropriately initialized for CF See enable compact flash Cf Enable Cf Disable Routine disables the device and frees the data lines for other devices To enable Description the device again call Cf Enable These two routines in conjunction allow you to free occupy data line when working with multiple devices Requires The corresponding MCU ports must be appropriately initialized for CF card See Cf Init disable compact flash Cf Disable MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 255 CHAPTER 6 Libraries mikroC PRO for AVR Cf Read Init void Cf Read Init unsigned long address unsigned short sector count Prototype Initializes CF card for reading Tm Parameters Description address the first sector to be prepared for reading operation sector count number of sectors to be prepared for reading operation Pi M MCU ports must be appropriately initialized for CF card See Example initialize compact flash for reading from sector 590 Example Read Init 590 1 Cf Read Byte Prototype unsigned short Cf Read Byte void Returns a byte read fro
109. RAM memory spaces space Register Space gt yo Space 2 SRAM Data Space 116 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 4 mikroC PRO for AVR AVR Specifics MEMORY TYPE SPECIFIERS The mikroC PRO for AVR supports usage of all memory areas Each variable may be explicitly assigned to a specific memory space by including a memory type specifier in the declaration or implicitly assigned The following memory type specifiers can be used code data rx LO sir Memory type specifiers can be included in variable declaration For example char data data_buffer puts data_buffer in data ram const char code txt ENTER PARAMETER puts text in program memory code Description The code memory type may be used for allocating constants in program memory puts txt in program memory const char code txt ENTER PARAME data Description This memory specifier is used when storing variable to the internal data SRAM puts PORTG in data ram sfr data unsigned short PORTG absolute 0x65 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 117 CHAPTER 4 AVR Specifics mikroC PRO for AVR rx This memory specifier allows variable to be stored in the Rx space Register file Description Note In most of the cases there will be enough space left for the user variables in the
110. SOLUTIONS FOR EMBEDDED WORLD 331 CHAPTER 6 Libraries mikroC PRO for AVR Mmc_Fat_Set_File_Date void Mmc Fat Set File Date unsigned int year unsigned short Prototype month unsigned short day unsigned short hours unsigned short mins unsigned short seconds o Writes system timestamp to a file Use this routine before each writing to file Description otherwise the file will be appended unknown timestamp The file must be assigned see Mmc_Fat_Assign Also file pointer must Requires tialized see Mmc Fat Reset April 1st 2005 18 07 00 Mmc Fat Set File Date 2005 4 Mmc Fat Get File Date void Mmc Fat Get File Date unsigned int year unsigned short Prototype month unsigned short day unsigned short hours unsigned short mins Retrieves date and time for the currently selected file Seconds not being Description retrieved since they are written in 2 sec increments The file must be assigned see Mmc Fat Assign get Date time of file unsigned yr char mnth dat hrs mins file Name MYFILEABTXT Mmc Fat Assign file Name Mmc Fat Get File Date yr mnth dat hrs mins 332 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Mmc Fat Get File Size Retums This uncon reuns size ofacive fie ntes get Date time of file unsigned yr
111. SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference Ini par po is same as int pa int pb int pc Once declared though a pointer can usually be reassigned so that it points to an object of another type The mikroC PRO for AVR lets you reassign pointers without typecasting but the compiler will warn you unless the pointer was originally declared to be pointing to void You can assign the void pointer to the non voia pointer refer to void for details Null Pointers A null pointer value is an address that is 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 sau The pointer type pointer to void must not be confused with the null pointer The declaration void vp declares that vp is a generic pointer capable of being assigned to by any pointer to type value including null without complaint Assignments without proper casting between a pointer to t yoe1 and a pointer to type2 where type1 and type2 are different types can invoke a compiler warning or error If is a function and type 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 is neede
112. SPI Glcd Set Side SPI Glcd Set X and SPI Glcd Set Page char data SPI Glcd Write Data data SPI Glcd Fill Prototype void SPI Glcd Fill char pattern Fills Glcd memory with byte pattern Parameters Description pattern byte to fill Glcd memory with To clear the Glcd screen use sP1 Fill 0 To fill the screen completely use SPI Gicd Fill OxFF Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Clear screen SPI Glcd Fill 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 457 CHAPTER 6 Libraries mikroC PRO for AVR SPI Glcd Dot Prototype void SPI Glcd Dot char x pos char y pos char color 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 Description color color parameter Valid values 0 2 The parameter color determines the dot state O 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 for SPI communication see SPI Glcd Init routines Invert the dot in the upper left corner SPI Glod Dot 0 0 2 SPI Glcd Line void SPI Glcd Line int x start int y start int x end int y end char color Draws a line on Glcd Parameters x start X coordinate of the line start Valid values 0 127 y start y
113. Sck Fosc 2 Master mode SPI FCY DIV2 Sck Fosc 8 Master mode FCY DIV8 Sck Fosc 32 Master mode SPI FCY DIV32 SPI clock polarity and phase constants lock i 1 Clock idle tevel is low sample SPI CLK LO LEADING on rising edge Clock idle 1 1 as db 1 0 04 BOUE Sampie SPI CLK LO TRAILING on falling edge 1 i ock idle LeveL is high sample SPI CLK HI LEADING on rising edge 0x0C Clock idle is high sample SPI CLK HI TRAILING on falling edge E ee Note Some SPI clock speeds are not supported by all AVR MCUs and these are Fosc 2 Fosc 8 Fosc 32 Please consult appropriate datasheet MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 427 CHAPTER 6 Libraries mikroC PRO for AVR MCU must have SPI module Set SPI to the Master Mode clock Fosc 32 clock idle level is high data sampled on falling edge 5 1 Init Advanced SPI MASTER SPI FCY DIV32 SPI CLK HI TRAIL SPI1 Read Prototype Description SPI Write ING char 5 1 Read char buffer Received data Reads one byte from the SPI bus Parameters buffer dummy data for clock generation see device Datasheet for SPI modules implementation details SPI module must be initialized before using this function See SPI1 Init and SPI1 Init Advanced routines read a byte from the SPI bus char take dummyl take
114. 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 T et s t O 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 amp 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 is 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 i e arrays are stored in rows Here is a sample of 2 dimensional array float m 50 20 2 dimensional array of size 50x20 156 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference 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 mi 011 0 the last one is m 49 19 The first element of the row
115. The termi nating null character is always appended to the result The function returns to strncpy Prototype char strncpy char to char from int size Function copies not more than size characters from string from to to If copy ing 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 Description strspn Prototype int strspn char strl char str2 Function returns the length of the maximum initial segment of str1 which con Description sists entirely of characters from str2 The terminating null character at the end of the string is not compared Strncmp Prototype int strncmp char 51 char s2 char len Function lexicographically compares not more than len characters characters that follow the null character are not compared from the string pointed by s1 to the string pointed by s2 The function returns a value indicating the s1 and s2 relationship Description Meaning S1 less than s2 sl equal to s2 sl greater than s2 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 557 CHAPTER 6 Libraries Strstr Prototype Description Strcspn Prototype Strpbrk Prototype Description Strrchr Prototype Description mikroC PRO for AVR char strstr char sl char s2 Function
116. UARTx Init Advanced void UARTx Init Advanced unsigned long baud rate char parity Prototype d char stop bits Configures and initializes UART module Parameter baud_rate configures UART module to work on a requested baud rate Parameters parity and stop bits determine the work mode for UART and can have the following values er Predefined library Description const Parity constants Description 0x00 Parity mode disabled UART NOPARITY 0x20 Even parity UART EVENPARITY 0x30 Odd parity UART ODDPARITY Stop bit constants 1 stop bit _UART_ONE_STOPBIT 2 stop bits _UART_TWO_STOPBITS Note Some MCUs do not support advanced configuration of the UART module Please consult appropriate daatsheet MCU must have UART module Initialize hardware UART1 module and establish communication at 9600 bps 8 bit data even parity and 2 STOP bits UART1 Init Advanced 9600 UART EVENPARITY UART TWO STOPBITS 536 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries UARTx_Data_Ready Returns Function returns 1 if data is ready or 0 if there is no data Use the function to test if data in receive buffer is ready for reading UART HW module must be initialized and communication established before using this function See UARTx Init If data is ready read it if UART1 Data Ready 1 receive UART1 Read
117. WINDOW In case that errors were encountered during compiling the compiler will report them and won t generate a hex file The Error Window will be prompted at the bottom of the main window by default The Error Window is located under message tab and displays location and type of errors the compiler has encountered The compiler also reports warnings but these do not affect the output only errors can interefere with the generation of hex Messages v Errors Warnings Hints Line Message No Message Text Unit 0 1 mikrocAVR exe MSF DBG 16 ES C 011111114 fo10 0 125 All files Preprocessed in 31 ms 0 121 Compilation Started Lcd c 21 399 expected but PORTB found Lcd c 22 399 expected but void found Lcd c 37 408 while expected but found Lcd c 38 402 expected but Found Lcd c 38 315 Invalid expression Lcd c 38 403 J expected but found Lcd c 36 399 expected but found Lcd c 38 421 expected found Lcd c 0 102 Finished with errors 18 Sep 2008 15 25 30 Lcd mcproj Double click the message line in the Error Window to highlight the line where the error was encountered Related topics Error Messages 52 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment STATISTICS After successful compilation you can review statistics of your code Click the Statis tics Icon falas Memory Usage Windows Provides ove
118. Write Text The following routine is for the internal use by compiler only UARTx TX Idle Note AVR MCUs require you to specify the module you want to use To select the desired UART simply change the letter x in the prototype for a number from 1 to 4 Number of UART modules per MCU differs from chip to chip Please read the appropriate datasheet before utilizing this library Example UART2 Init initializes UART 2 module Note Some of the AVR MCUs do not support UARTx Init Advanced routine Please refer to the appropriate datasheet 534 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries UARTX Init Prototype Description void UARTx Init unsigned long baud rate Nothing Configures and initializes the UART module The internal UART module module is set to receiver enabled transmitter enabled frame size 8 bits 1 STOP bit parity mode disabled asynchronous operation Parameters baud rate requested baud rate Refer to the device data sheet for baud rates allowed for specific Fosc You ll need AVR MCU with hardware UART UARTx Init needs to be called before using other functions from UART Library This will initialize hardware UART1 module and establish the communication at 2400 bps UART1 Init 2400 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 535 CHAPTER 6 Libraries mikroC PRO for AVR
119. a part of the program 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 declaration point and ends at the end of the block containing the declara tion 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 dec larations 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 is a region of the program source code from which an identifier s associated object can be legally accessed Scope and visibility usually co
120. an integer while remainder is simply truncated MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 195 CHAPTER 5 Language Reference mikroC PRO for AVR for example 7 4 equals 1 Tow Bf 4 equals 5 but 7 4 equals 5 25 because we are working with floats Remainder operand works only with integers the sign of result is equal to the sign of the first operand for example 9 3 equals 0 7 3 equals 1 7 3 equals 1 Arithmetic operators can be used for manipulating characters 32 equals a ASCII only G a equals g both ASCII and EBCDIC Unary Arithmetic Operators Unary operators and are the only operators in C which can be either prefix e g 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 j k k 1 j which gives us j 6 k 6 but int j 5 j k j k 1 which gives us j 5 k 196 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference RELATIONAL OPERATORS
121. are used in cell phones mp3 players digital cameras and PDA s mikroC PRO for AVR provides a library for accessing data on Multi Media Card via SPI communication This library also supports SD Secure Digital memory cards Secure Digital Card Secure Digital SD is a flash memory card standard based on the older Multi Media Card MMC format SD cards are currently available in sizes of up to and including 2 GB and are used in cell phones mp3 players digital cameras and PDAs Notes Routines for file handling can be used only with FAT16 file system Library functions create and read files from the root directory only Library functions populate both FAT1 and FAT2 tables when writing to files but the file data is being read from the FAT1 table only i e there is no recovery if FAT 1 table is corrupted Prior to calling any of this library routines Spi Rd Ptr needs to be initial ized with the appropriate SPI Read routine External dependecies of MMC Library The following variables must be defined in all projects using Description Manchester Code Library extern sfr sbit sbit Mmc Chio Select Chip select pin Mmc Chip Select at ii PORTG B1 sbit extern sfr sbit Direction of the chip Chip Select Di Mmc Chip Select Direction select pin rection at DDRG B1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Libraries 323 CHAPTER 6 Libraries mikroC PRO for AVR Librar
122. be created Note Long File Names LFN are not supported CF card and CF library must be initialized for file operations See Cf_Fat_Init create file with archive attributes if it does not already exist Cf Fat Assign MIKROOO7 TXT OxA0 260 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Cf_Fat_Reset Prototype void Cf Fat Reset unsigned long size Opens currently assigned file for reading T Parameters Description size buffer to store file size to After file has been open for reading its size is returned through this parameter CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign unsigned long size Cf Fat Reset size Cf Fat Read Prototype void Cf Fat Read unsigned short bdata Reads a byte from currently assigned file opened for reading Upon function execution file pointers will be set to the next character in the file Description Parameters bdata buffer to store read byte to Upon this function execution read byte is returned through this parameter CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign File must be open for reading See Cf Fat Reset char character Cf Fat Read amp character MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLU
123. bit access see Accessing Individual Bits for more information Bit Fields Declaration Bit fields can be declared only in structures and unions Declare a structure normal ly and assign individual fields like this fields need to be unsigned struct tag unsigned bitfield declarator list Here tag is an optional name of the structure bitfield declarator list is a 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 As an object bit fields structure takes two bytes Individual fields are packed within two bytes from right to left In bitfield declarator list you can omit identifier s to create an artificial padding thus skipping irrelevant bits For example if there is 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 172 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference typedef struct lo nibble 4 hi nibble 4 high byte 8 myunsigned which declares the structured type myunsigned containing three components lo nibble bits 3 0 ni nibble bits 7 4 and high byte bits 15 8
124. call limit Clock MHz Prototype unsigned short Clock MHz void Returns Device clock in MHz rounded to the nearest integer Function returns device clock in MHz rounded to the nearest integer Description This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 109 CHAPTER 3 Specifics mikroC PRO for AVR Get_Fosc_kHz Prototype unsigned long Get Fosc kHz void Returns Device clock in kHz rounded to the nearest integer Function returns device clock in kHz rounded to the nearest integer Description Note that Fosc is library function rather than a built in routine it is pre sented in this topic for the sake of convenience Example ax moe 7 CODE OPTIMIZATION Optimizer has been added to extend the compiler usability cut down the amount of code gener ated and speed up its execution The main features are Constant folding All expressions that can be evaluated in the compile time i e are constant are being replaced by their results 3 5 gt 8 Constant propagation When a constant value is being assigned to a certain variable the compiler recognizes this and replaces the use of the variable by constant in the code that follows as long as the value of a vari able remains unchanged Copy p
125. can be assigned only if the source and desti nation have the same type aa aaa OK same type member by member assignment aa bb ILLEGAL different types but you can assign member by member aa i bb i aa j bb j aa d bb d MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 169 CHAPTER 5 Language Reference mikroC PRO for AVR 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 mem ory space Note The mikroC PRO for AVR does not support anonymous unions ANSI diver gence 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 ine double d char ch mu pm The identifier mu of the type myunion can be used to hold a 2 byte int 4 byte dou ble or single byte char but only one of them at a certain moment The identifier pm is a pointer to union myunion Size of Union The size of a union is the size of its largest member In our previous example both sizeof union myunion and sizeof mu return 4 but 2 bytes are unused padded when mu holds the int object and 3 bytes are unused
126. card and MMC FAT16 library glob als if SPI FCY DIV128 SPI CLK LO Li Mmc Fat QuickFormat amp mmc fat label Reinitialize the SPI module at higher speed prescaler SPI1 Init Advanced SPI MASTER ING change primary SPI FCY DIV2 SPI LO LEAD 328 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Mmc_Fat_Assign Prototype Description CHAPTER 6 Libraries unsigned short Mmc Fat Assign char filename char file ore attr 1 if file already exists or file does not exist but new file is created 0 if file does not exist and no new file is created Assigns file for file operations read write delete All subsequent file opera tions will be applied over the assigned file Parameters filename name of the file that should be assigned for file operations File name should be in DOS 8 3 file name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does no have to take care of that The file name and extension are case insensitive The library will convert them to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with first version of this library file names can be entered as UPPERCASE string of 11 bytes in length
127. choosing pull up down resistors configuration PortA pull up down resistors configuration is passed in 110 5 5 higher byte PortB pull up down resistors configuration is passed in PullUps s lower byte Each bit corresponds to the appropriate pin of the PortA PortB register Set bit enables pull up for corresponding pin Requires Port Expander must be initialized See Expander Init Example Set Port Expander s PORTA and PORTB pull up resistors Expander Set _PullUpsPortAB 0 OxFFFF MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 363 CHAPTER 6 Libraries mikroC PRO for AVR Library Example The example demonstrates how to communicate with Port Expander 23517 Note that Port Expander pins A2 A1 AO are connected to GND so Port Expander Hardware Address is 0 Port Expander module connections sbit SPExpanderRST at PORTB BO sbit SPExpanderCS at PORTB B1 Sbit SPExpanderRST Direction at DDRB B0 sbit SPExpanderCS Direction at DDRB B1 End Port Expander module connections Pointer to appropriate SPI Read function char SPI Rd Ptr char unsigned char i 0 void main DDRC OxFF Set PORTC as output If Port Expander Library uses SPI1 module SPI Inrt Initialize SPI module used with PortExpander SPI Rd Ptr amp SPI1 Read Pass pointer to SPI Read function of used SPI module If Port Expander Library uses SPI2 module SPI2 Init
128. cursor position Both variables and literals can be passed as a character Daseripion Parameters out char character to be written The Lcd module needs to be initialized See Lcd Init routine Write character e at current cursor position Lcd Chr Cp e MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 309 CHAPTER 6 Libraries mikroC PRO for AVR Lcd Cmd Sends command to Lcd Parameters Description 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 table Clear Lcd display Lcd Cmd LCD CLEAR Available Lcd Commands G URSOR OFF Turn off cursor L ERLINE ON Underline cursor on NK CURSOR ON Blink cursor on D MOVE CURSOR LI Move cursor left without changing display data RAM D SE LCD T LCD FO Return cursor to home position returns a shifted display to its original position Display data RAM is unaffected LCD C D UND D BLI Move cursor right without changing display data RAM C L i L Shift display left without changing display data RAM Shift display right without changing display data RAM 310 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Library Example The following code demonstrates usage of the Lcd Libr
129. example at the bottom of this page set the appropriate filter mask and message type valu CANSPISetOperationMode CANSPI MODE CONFIG OxFF yd set CONFIGURATION mode CANSPI module must be in config mode for mask settings Set all Bl mask bits to 1 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 Bl 1 CANSPI CONFIG MATCH MSG TYPE CANSPI CONFIG XTD MSG 240 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries CANSPISetFilter void CANSPISetFilter char CAN FILTER long val char CAN CONFIG FLAGS Nothing Configures message filter The parameter value is bit adjusted to the appropri ate filter registers Parameters FILTER CANSPI module filter number Valid values 5 FILTER Con stants see CANSPI constants Description va1 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 The CANSPI module must be in Config mode otherwise the function will be ignored See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has
130. files and writes data to them void M Create Multiple Files for loop2 B loop2 lt Z UART1 Write loop2 filename 7 loop2 Mmc Fat Assign amp filename 0 0 create a new one Mmc Fat Rewrite with new data for loop 1 loop lt 44 1 file contents 0 loop 10 file contents 1 loop 10 Mmc Fat Write file contents 42 file Opens existing file and rewrites void M Open File Rewrite filename 7 HET S loop2 signal the progress set filename find existing file or To clear file and start 48 48 write data to the assigned it Mmc Fat Assign amp filename 0 Mmc Fat Rewrite for loop 1 loop lt 55 looptt file contents 0 loop 10 64 file contents 1 loop 10 64 Mmc Fat Write file contents 42 write data to the assigned tale Opens an existing file and appends data to it 721 and alters the date time stamp void M Open File Append filename 7 Mmc Fat Assign amp filename 0 Mmc Fat Set File Date 2005 6 21 10 35 0 Mmc Fat Append file for append Mmc Fat Write data to assigned file n M M M Opens an existing file it to USART void M Open File Read filename 7 Mmc Fat Assign amp filename Mmc Fat Reset amp size returns size of file 0 for mikroElektronika 2005n Pre
131. files test h Note There is also a third version of the include directive rarely used which assumes that neither lt nor appear as the first non whitespace character following include include macro identifier It assumes that macro definition that will expand macro identifier into a valid delimit ed header name with either neader name gt or header name formats exists MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 223 CHAPTER 5 Language Reference mikroC PRO for AVR PREPROCESSOR OPERATORS The pound sign is a preprocessor directive when it occurs as the first non white space character on a line Also and perform operator replacement and merg ing during the preprocessor scanning phase Operator In C preprocessor a character sequence enclosed by quotes is considered a token and its content is not analyzed This means that macro names within quotes are not expanded If you need an actual argument the exact sequence of characters within quotes as a result of preprocessing use the operator in macro body It can be placed in front of a formal macro argument in definition in order to convert the actual argument to a string after replacement For example let s have macro PRINT for printing variable name and value on LCD define LCD PRINT val Lcd Custom Out Cp val N Lcd Custom Out Cp IntToStr val Now the following code LCD PRINT temp will be preproce
132. has only PWM library Therefore constants that have in their name PWM1 are invalid for ATmega8515 and will not be visible from Code Assistant It is highly advis able to use this feature since it handles all the constants available nad eliminates any chance of typing error PWM Init Protot void PWM Init unsigned short wave mode unsigned short prescaler ototype unsigned short inverted unsigned short duty Initializes the PWM module Parameter wave mode is a desired PWM mode There are two modes Phase Correct and Fast PWM Parameter prescaler chooses prescale value N 1 8 64 256 or 1024 some modules support 32 and 128 but for this you will need to check the datasheet for the desired MCU Paremeter inverted is for choosing between inverted and non inverted PWM signal Parameter duty sets duty ratio from 0 to 255 PWM signal graphs and formulas are shown below PHASE f fak i o MODE em N 510 2554 Duty Ratio 7 4 4 EJ Descri ption 3tew M 4t M PNM 7 tow M Non Inverted vere The variable represents the prescaler factor 1 8 64 256 1024 Some modules also support 32 and 128 prescaler value but for this you will need to check the datasheet for the desired MCU 374 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries i o fomm 256 A 1 2tew M 3tewm 4tew
133. initialized See Ps2 Config routine unsigned short value special pressed Press Enter to continue do if Ps2 Key Read amp value amp special amp pressed if value 13 amp amp special 1 break while 1 368 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Special Function Keys Value returned 1 2 3 4 5 Page Up Page Down Backspace Insert Print Screen Pause Caps Lock Home CHAPTER 6 Libraries Scroll Lock Num Lock Left Arrow Right Arrow Up Arrow Down Arrow Escape Tab MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 369 CHAPTER 6 Libraries mikroC PRO for AVR Library Example This simple example reads values of the pressed keys on the PS 2 keyboard and sends them via UART unsigned short keydata 0 special 0 down 0 sbit PS2 Data at PINC B0 sbit 52 In Clock at PINC B1 sbit PS2 Out Clock at FPORTC B1 sbit PS2 Data Direction at DDRC B0 sbit PS2 Clock Direction at DDRC B1 void main ACSR B7 1 Disable analog comparators SREG B7 0 Disable all interrupts UART1 Init 19200 Ps2 Config Init PS 2 Keyboard on PORTC Delay ms 100 Wait for keyboard to finish UART1 Write R Ready do if Ps2 Key Read amp keydata amp special amp down if down amp amp keydata 16 Backspace UART1 Write 0x08 else if
134. is treated as a regular character Examples count r R matches strings like counter countelkjdflkj9r and counts count r matches strings like counter countelkjdflkj9r but not count r matches strings like counter countar and countr but not countelkj9r CHAPTER 2 mikroC PRO for AVR Environment counte 2 r matches string counteer counte 2 matches strings like counteer counteeer counteeer etc counte 2 3 r matches strings like counteer Or counteeer but not counteeeer A little explanation about greediness Greedy takes as many as possible non greedy takes as few as possible For example b and b applied to string abbbbc return bbbb returns b b returns empty string 2 3 returns bb b 2 3 returns bbb Metacharacters Alternatives You can specify a series of alternatives for a pattern using to separate them so that 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 minimize confusion about where they start and end Alternatives are t
135. linkage rules have external linkage 180 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference The storage class specifiers auto and register Cannot appear in an external dec laration No more than one external definition 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 in 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 attrib utes storage class and type sometimes referred to as data type The mikroC PRO for AVR compiler deduces these attributes from implicit or explicit declarations in the source code A storage class dictates the location data segment register heap or stack of object and its duration or lifetime the entire running time of the program or during execution of some blocks of code A storage class can be established by the syn tax of a declaration by its placement in the source code or by both of these factors storage class type identifier The storage class specifiers in the mikroC PRO for AVR are auto register static ex
136. lower right box corner y1 y coordinate of the lower right box corner pcolor color parameter Valid values SPI TG963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine E cm T6963C Box 0 119 239 T6963C WHITE SPI T6963C Circle Description void SPI T6963C Circle int x int y long r unsigned char pcol or Draws a circle on the Glcd Parameters Description x X coordinate of the circle center y y coordinate of the circle center r radius size pcolor color parameter Valid values SPI TG963C BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine _16963 _ 1 1 120 64 110 T6963C WHITE 492 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI_T6963C_Image Prototype void SPI T6963C Image const code char pic 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 PRO for AVR pointer to const and pointer to RAM equivalency Description Use the mikroC PRO s integrated Glcd Bitmap Editor menu option Tools Glcd Bitmap Editor to convert image to a constant array suitable for displaying on Glcd Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example SPI T6963C Sprite void SPI T69
137. mikroElektronika s Keypad extra board HW Rev v1 20 External dependencies of Keypad Library The following variable must be defined in all projects Description using Keypad Library extern sfr char sfr char keypadPort keypadPort Keypad Port at PORTB sfr char extern sfr char Direction of the Key keypadPort Direction d Port Ore XE on at DDRB Library Routines Keypad Init Keypad Key Press Keypad Key Click MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 299 CHAPTER 6 Libraries mikroC PRO for AVR Keypad Init 300 Prototype Initializes port for working with keypad Global variables keypadPort Keypad port Requires keypadPort Direction Direction of the Keypad port must be defined before using this function Initialize PORTB for communication with keypad sfr char keypadPort at PORTB Port direction sfr char keypadPort Direction at DDRB LCD module connections sbit LCD RS at PORTD B2 sbit LCD EN at PORTD B3 sbit LC D4 at PORTD B4 sbit LCD D5 at PORTD B5 sbit LCD D6 at PORTD B6 sbit LCD D7 at PORTD B7 sbit LC S Direction at DDRD B2 sbit LCD EN Direction at DDRD B3 sbit LCD D4 Direction at DDRD 4 sbit LCD D5 Direction at DDRD B5 sbit LCD D6 Direction at DDRD B6 sbit LCD D7 Direction at DDRD End LCD module connections Keypad Init MIKROELEKTRONIKA SOFTWARE AND H
138. 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 CANSPISetBaudRate 1 1 3 3 1 can config flags MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 239 CHAPTER 6 Libraries mikroC PRO for AVR CANSPISetMask Prototype Description void CANSPISetMask char CAN MASK long val char CAN CONFIG FLAGS Nothing Configures mask for advanced filtering of messages The parameter value is bit adjusted to the appropriate mask registers Parameters CAN MASK CANSPI module mask number Valid values CANSPI_MASK con stants 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 TYPE amp CANSPI CONFIG STD MSG CANSPI CONFIG MATCH MSG TYPE amp CANSPI CONFIG XTD MSG see CANSPI constants The CANSPI module must be in Config mode otherwise the function will be ignored See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection
139. 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 Enumerations Void Type ARITHMETIC TYPES The arithmetic type specifiers are built up from the following keywords void char int float and double together with the prefixes short long signed and unsigned From these keywords you can build both integral and floating point types Integral Types The types char and int together with their variants are considered to be integral data types Variants are created by using one of the prefix modifiers short long signed and unsigned In the table below is an overview of the integral types keywords in parentheses can be and often are omitted The modifiers signed and unsigned can be applied to both char and int In the absence of the unsigned prefix signed is automatically assumed for integral types The only exception is char which is unsigned by default The keywords signed and unsigned when used on their own mean signed int and unsigned int respectively The modifiers short and long can only be applied to int The keywords short and long used on their own mean short int and long int respectively 150 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPT
140. network interface for any controller equipped with SPI The 28760 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 designed to simplify handling of the underlying hardware ENC28J60 It works with any AVR MCU with integrated SPI and more than 4 Kb ROM memory SPI Ethernet library supports IPv4 protocol ARP requests ICMP echo requests UDP requests TCP requests no stack no packet reconstruction packet fragmentation is NOT supported Note For advanced users there are header files eth enc28j60LibDef h and eth enc28j60LibPrivate h in Uses folder of the compiler with description of all rou tines 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 Note The appropriate hardware SPI module must be initialized before using any of the SPI Ethernet library routines Refer to SPI Library MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUT
141. of this page Nothing Software I2C connections sbit Soft I2C Scl Output at PORTC BO sbit Soft I2C Sda Output at 1 sbit Soft I2C Scl Input at PINC B0 sbit Soft I2C Sda Input at sbit Soft I2C Scl Direction at DDRC B0 it Soft I2C Sda Direction at DDRC B1 End Software I2C connections char counter 0 void TimerOOverflow ISR org 0x12 if counter gt 20 Soft I2C Break counter 0 reset counter else increment counter void main TOIEO bit TimerO overflow interrupt enable TCCRO bat Start timer with 1024 prescaler SREG I bt 0 Interrupt disable try Soft I2C Init with blocking prevention mechanism SREG I bit 1 Interrupt enable Soft I2C Init SREG I bit 0 Interrupt disable 406 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Library Example The example demonstrates Software 1 Library routines usage The AVR MCU is connected SCL SDA pins to PCF8583 RTC real time clock Program reads date and time are read from the RTC and prints it on LCD char seconds minutes hours day month year Global date time variables Software I2C connections sbit Soft I2C Scl Output at PORTC B0 sbit Soft I2C Sda Output at PORTC B1 sbit Soft I2C Scl Input at PINC BO sbit Soft I2C Sda Input at PINC B1 sbit Soft I2C
142. pin Library Routines Soft UART Init Soft UART Read UART Write Soft UART Break MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 415 CHAPTER 6 Libraries Soft_UART_ Prototype Description mikroC PRO for AVR Init char Soft UART Init unsigned long baud rate char inverted 2 error requested baud rate is too low 1 error requested baud rate is too high 0 successfull initialization Configures and initializes the software UART module Parameters baud rate baud rate to be set Maximum baud rate depends on the MCU S clock and working conditions inverted inverted output flag When set to a non zero value inverted logic on output is used Software UART routines use Delay routine If requested baud rate is too low then calculated parameter for calling Delay Cyc exceeeds Delay Cyc argu ment range If requested baud rate is too high then rounding error of Delay Cyc argument corrupts Software UART timings Global variables Soft UART Rx Pin Receiver pin Soft UART Tx Pin Transmiter pin Soft UART Rx Pin Direction Direction of the Receiver pin Soft UART Tx Pin Direction Direction of the Transmiter pin must be defined before using this function Soft UART connections sbit Soft UART Rx Pin at PIND B0 sbit Soft UART Tx Pin at PORTD B1 sbit Soft UART Rx Pin Direction at DDRD B0 sbit Soft UART Tx Pin Direction at DDRD
143. 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 ENC28760 module The ENc28760 module should be properly cofigured by the means of SPI Ethernet Init routine CHAPTER 6 mikroC PRO for AVR Libraries Ethernet module has to be initialized See SPI Ethernet Init SPI Ethernet Enable SPI Ethernet CRC SPI Ethernet UNICAST enable CRC checking and Unicast traffic SPI Ethernet Disable Prototype void SPI Ethernet Disable unsigned char disFlt This is MAC module routine This routine disables appropriate network traffic on the ENC28760 module by the means of it s receive filters unicast multicast broad cast crc Specific type of network traffic will be disabled if a corresponding bit of this routine s input parameter is set Therefore more than one type of network traffic can be disabled at the same time For this purpose predefined library con stants see the table below can be ORed to form appropriate input value Parameters disFlt network traffic receive filter flags Each bit corresponds to the appropriate network traffic receive filter m Predefined library Description const 0 MAC Broadcast traffic receive filter flag When 5 Ethernet BRO set MAC broadcast traffic will be disabled ADCAST i MAC Multicast traffic receive filter flag When 5 Ethernet MUL Des
144. serial number and 8 bit CRC so multiple slaves can co exist on the same bus Note Oscillator frequency Fosc needs to be at least 8MHz in order to use the rou tines with Dallas digital thermometers External dependencies of OneWire Library The following variables must be defined in all projects using Description Manchester Code Library sbit OW Bit Read extern sfr sbit OW Bit Read OneWire read line at PINB B2 extern sfr sbit OneWire write line sbit OW Bit Write OW Bit Write at PORTB B2 extern sfr sbit Direction of the Sbit OW Bit Di ti OneWi OW Bit Direction OEE EES CR EON Nerve pun at DDRB B2 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 347 CHAPTER 6 Libraries mikroC PRO for AVR Library Routines Ow_Reset Ow_Read Ow_Write Ow_Reset Prototype unsigned short Ow Reset 0 if the device is present 1 if the device is not present Issues OneWire reset signal for DS18x20 Description Parameters Devices compliant with the Dallas OneWire protocol Global variables OW Bit Read OneWire read line OW Bit Write OneWire write line OW Bit Direction Direction of the OneWire pin must be defined before using this function Issue Reset signal on One Wire Bus Ow Reset 348 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Ow_Read Returns Data read from an external
145. size my file size Cf Fat Get File Size 266 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Cf_Fat_Get_Swap File Prototype unsigned long Cf Fat Get Swap File unsigned long sectors cnt yp char filename char file attr Number of the start sector for the newly created swap file if there was enough free space on CF card to create file of required size 0 otherwise This function is used to create a swap file of predefined name and size on the CF media If a file with specified name already exists on the media search for consecutive sectors will ignore sectors occupied by this file Therefore it is rec ommended to erase such file if it exists before calling this function If it is not erased and there is still enough space for a new swap file this function will delete it after allocating new memory space for a new swap file The purpose of the swap file is to make reading and writing to CF media as fast as possible by using the Cf_Read_Sector and Cf_Write_Sector functions directly without potentially damaging the FAT system Swap file can be consid ered as a window on the media where the user can freely write read data It s main purpose in the mikroC s library is to be used for fast data acquisition when the time critical acquisition has finished the data can be re written into a nor mal file and formatted in the most suitable way Pa
146. starting from the innermost conditional with each else bound to the nearest available i on its left if expressionl statementl lse if expression2 if expression3 statement2 else statement3 this belongs to if expression3 else statement4 this belongs to if expression2 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 210 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference SWITCH STATEMENT The switch statement is used to pass control to a specific program branch based on a certain condition The syntax of the switch statement is switch expression case constant expression 1 statement 1 case constant expression n statement n default statement First the expression condition is evaluated The switch statement then com pares it to all available constant expressions following the keyword case If a match is found switch passes control to that matching case causing the state ment following the match evaluates Note that constant expressions must evalu ate to integer It is not possible to have two same constant expressions evaluating to the same value Parentheses around expression are mandatory Upon finding a match program flow continues normally the follo
147. the call doesn t count against the nested call limit Example Delay ms 1000 One second pause Vdelay ms Prototype vdelay ms unsigned time in ms Creates a software delay in duration of time in ms milliseconds a variable Generated delay is not as precise as the delay created by Delay ms Description Note that vaelay ms is library function rather than a built in routine it is present ed in this topic for the sake of convenience pause 1000 Vdelay ms pause one second pause MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroC PRO for AVR Specifics Delay_Cyc Prototype void Delay Cyc char Cycles div by 10 Creates a delay based on MCU clock Delay lasts for 10 times the input param eter in MCU cycles Descnption Note that Delay Cyc is library function rather than a built in routine it is present ed in this topic for the sake of convenience There are limitations for Cycles div by 10 value Value Cycles div by 10 must be between 2 and 257 Requires Nothing Example peiay 10 Hundred MCU cycles pause Clock kHz Prototype unsigned Clock kHz void Retr Deve dk ne ene he nears eget Function returns device clock in kHz rounded to the nearest integer Description This is an inline routine code is generated in the place of the call so the call doesn t count against the nested
148. the desired MCU before you start writ ing your code Compiler automatically takes care of appropiate instruction set and if unapropriate asm instruction is used in in line assembly co mpiler will report an error Program counter size is MCU dependent Thus there are two sets of libraries MCUs with program counter size larger than 16 bits flash memo ry size larger than 128kb MCUs with program counter size less or equal 16 bits flash mem ory size smaller than 128kb Assembly SPM instruction and its derivates must reside in Boot Loader section of program memory Part of flash memory can be dedicated to Boot Loader code For details refer to AVR memory organization Related topics mikroC PRO for AVR specifics AVR memory organization 114 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 4 mikroC PRO for AVR AVR Specifics AVR MEMORY ORGANIZATION The AVR microcontrollers memory is divided into Program Memory and Data Memory Program Memory ROM is used for permanent saving program being exe cuted while Data Memory RAM is used for temporarily storing and keeping inter mediate results and variables Program Memory ROM Program Memory ROM is used for permanent saving program CODE being exe cuted and it is divided into two sections Boot Program section and the Application Program section The size of these sections is configured by the BOOTSZ fuse These two sections can ha
149. to a certain point in the code see File Inclusion replacing specific lexical symbols with other symbols see Macros conditional compiling which conditionally includes or omits parts of the code see Conditional Compilation Note that preprocessor analyzes text at token level not at individual character level Preprocessor is controled by means of preprocessor directives and preprocessor operators 218 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference PREPROCESSOR DIRECTIVES Any line in the source code with a leading is taken as a preprocessing directive or control line unless is within a string literal in a character constant or embedded in a comment The initial can be preceded or followed by a whitespace excluding new lines A null directive consists of a line containing the single character This line is always ignored Preprocessor directives are usually placed at the beginning of the source code but they can legally appear at any point in a program The mikroC PRO for AVR pre processor detects preprocessor directives and parses the tokens embedded in them A directive is in effect from its declaration to the end of the program file Here is one commonly used directive include math h For more information on including files with the include directive refer to File Inclusion The mikroC PRO for AVR supports standard prepr
150. to be associated cor rectly with one particular object or function All identifiers have one of two linkage attrib utes closely related to their scope external linkage or internal linkage These attributes are determined by the placement and format of your declarations together with an explicit or implicit by default use of the storage class specifier static or extern Each instance of a particular identifier with external linkage represents the same object or function throughout the entire set of files and libraries making up the 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 3 typedef names have internal linkage 4 enumeration constants have internal linkage External Linkage Rules 1 names having file scope that do not comply to any of previously stated internal
151. to be initialized see Glcd Init routine The following two lines are equivalent and both of them select the left side of Glcd Glcd Select Side 0 Gled Select Side 10 Glcd Set X Prototype void Glcd Set X unsigned short x pos Sets x axis position to x pos dots from the left border of Glcd within the select ed side Parameters Description x pos position on x axis Valid values 0 63 Note For side x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized see Glcd Init routine faseen O MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 285 CHAPTER 6 Libraries mikroC PRO for AVR Glcd Set Page Prototype Glcd Set Page unsigned short page Selects page of the Glcd Parameters Description page page number Valid values 0 7 Note For side x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized see Glcd Init routine Example 4 Glcd Read Data Returns One byte from Glcd memory 42 Reads data from from the current location of Glcd memory and moves to the Description next location Glcd needs to be initialized see Glcd Init routine Glcd side x axis position and page should be set first See functions Set Side Glcd Set X and Glcd Set Page unsigned short data data Glcd Read Data
152. to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page set the appropriate filter value and message type CANSPISetOperationMode CANSPI MODE CONFIG OxFF set CONFIGURATION mode CANSPI module must be in config mode for filter settings Set id of filter Bl F1 to 3 CANSPISetFilter CANSPI FILTER Bl Fl 3 CANSPI CONFIG XTD MSG MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 241 CHAPTER 6 Libraries mikroC PRO for AVR CANSPIRead Prototype Description char CANSPIRead long id char rd data char data len char CAN RX MSG FLAGS 0 if nothing is received 0xFF if one of the Receive Buffers is full message received If at least one full Receive Buffer is found it will be processed in the following way Message ID is retrieved and stored to location provided by the id parameter Message data is retrieved and stored to a buffer provided by the rd parameter Message length is retrieved and stored to location provided by the data 1en 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 The CANSPI module must
153. txt GLCD LIBRARY DEMO WELCOME unsigned char panel Current panel unsigned int iy General purpose register unsigned char curs Cursor visibility unsigned int cposx cposy Cursor x y position MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 525 CHAPTER 6 Libraries mikroC PRO for AVR DDBO DDB1 DDB2 DDB3 DDB4 M Ne Ne OO OGO e T6963C ctrlce Direction T6963C ctrlce 0 T6963C ctrlfs Direction T6963C ctrlfs 0 T6963C ctrlmd Direction T6963C ctrlmd 0 Initialize T6369C T6963C init 240 128 8 Enable both graphics T6963C graphics 1 T6963C text 1 panel 0 i 0 curs 0 cposx cposy 0 Text messages ud th Set Set Set Set Set PBO 1 PB2 PB3 PB4 as as as as as input input input input input Enable T6963C Font Select 8x8 Column number select text display at the same time T6963C write text txt 0 0 T6963C ROM MODE XOR T6963C write text txtl 0 15 T6963C ROM MODE XOR Cursor T6963C cursor height 8 8 pixel height T6963C set cursor 0 0 Move cursor to top left T6963C cursor 0 Cursor off Draw rectangles uA T6963C rectangle 0 0 239 127 T6963C WHITE T6963C rectangle 20 20 219 107 T6963C WHITE T6963C rectangle 40 40 199 87 T6963C WHITE T6963C rectangle 60 60
154. user 119 CHAPTER 5 Language Reference mikroC PRO for AVR MIKROC PRO FOR AVR LANGUAGE REFERENCE Lexical Elements Whitespace Comments Tokens Constants Constants Overview Integer Constants Floating Point Constants Character Constants String Constants Enumeration Constants Pointer Constants Constant Expressions Keywords Identifiers Punctuators Concepts Objects and Lvalues Scope and Visibility Name Spaces Duration Types Fundamental Types Arithmetic Types Enumerations Void Type Derived Types Arrays Pointers Introduction to Pointers Pointer Arithmetic Structures Introduction to Structures Working with Structures Structure Member Access Unions Bit Fields Types Conversions Standard Conversions Explicit Typecasting Declarations Introduction to Declarations 120 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference Linkage Storage Classes Type Qualifiers Typedef Specifier ASM Declaration Initialization Functions Introduction to Functions Function Calls and Argument Conversion Operators Introduction to Operators Operators Precedence and Associativity Arithmetic Operators Relational Operators Bitwise Operators Logical Operators Conditional Operator Assignment Operators Sizeof Operator Expressions Introduction to Expressions Comma Expressions Statements Introduction Labeled Statements Expression Statements Selection Statements If St
155. 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 can be used in subsequent declarations of enumeration variables of the enum col ors type enum colors bg border declare variables 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 Enu merators share the same name space as ordinary variable identifiers int blue 73 open a block enum colors black red green blue violet white c enumerator blue 3 now hides outer declaration of int blue struct colors int i J7 Y ILLEGAL colors duplicate tag double red 2 ILLEGAL redefinition of red blue 37 back in int blue scope MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 153 CHAPTER 5 Language Reference mikroC PRO for AVR VOID TYPE void is a special type indicating the absence of any value There are no objects of void instead void is used for deriving more complex types Void Functions Use the void keyword as a function return type if the function does not return a value void print temp char temp Lcd Out Cp Temperature
156. void SPI Glcd Write Char char chrl char x pos char page num char color Prints character on Glcd Prototype 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 Description values 0 7 color color parameter Valid values 0 2 The parameter color determines the color of the character 0 white 1 black and 2 inverts each dot Note For x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Use the SPI Glcd Set Font to specify the font for display if no font is specified then the default 5x8 font supplied with the library will be used Write character C on the position 10 inside the page 2 SPI Glod Write Char C 10 2 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 463 CHAPTER 6 Libraries mikroC PRO for AVR SPI Glcd Write Text Prototype Description void SPI Glcd Write Text char text char x pos char page num char color Nothing Prints text on Glcd Parameters text text to be written x pos text starting position on x axis page num the number of the page on which text will be written Valid values 0 7 color color parameter Valid values 0 2 The parameter color determines the colo
157. 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 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 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 Cf Init char ctrlport char dataport makes it clear If a header file contains function prototypes the user can read that file to get the information needed for writing programs that call these functions If a prototype parameter includes an identifier then the indentifier is only used for error checking
158. x on control port if bit x in bit mask is set to 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine clear bits 0 and 1 on control port SPI T6963C ClearBit 0x03 494 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI_T6963C_SetBit Prototype 5 T6963C SetBit char Nothing Sets control port bit s Parameters Description b bit mask The function will set bit x on control port if bit x in bit mask is set to 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set bits 0 and 1 on control port SPI T6963C SetBit 0x03 SPI T6963C NegBit Prototype 5 T6963C NegBit char Nothing Negates control port bit s Description Parameters b bit mask The function will negate bit x on control port if bit x in bit mask is set to 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine negate bits 0 and 1 on control port SPI T6963C NegBit 0x03 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 495 CHAPTER 6 Libraries mikroC PRO for AVR SPI_T6963C_DisplayGrPanel Prototype void SPI T6963C DisplayGrPanel char n Nothing Display selected graphic panel Description Parameters n graphic panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized Se
159. 0 0x0800 0x0900 0x0A00 0x0B00 0x0C00 0x0D00 0x0E00 0x0F00 absolute 0x200 char i unsigned int word unsigned int dat buff 32 void main DDRD OxFF set direction to be output DDRB OxFF set direction to be output word data 0 link const table 280 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries for i 0 i 64 i422 reading 32 words in loop word FLASH Read Word F ADDRESS i demonstration of reading single word PORTD word output low byte to PORTD PORTB word gt gt 8 output higher byte to PORTB Delay ms 200 1 0 while i lt 64 reading 64 bytes in loop PORTD FLASH Read Byte F ADDRESS i demonstration of reading single byte PORTB FLASH Read Byte F ADDRESS of reading single byte Delay ms 200 demonstration t H t FLASH Read Bytes F ADDRESS dat buff 64 demonstration of reading 64 bytes for i 0 1 lt 32 7 i PORTD dat buff i output low byte to PORTD PORTB dat_buff i gt gt 8 output higher byte to PORTB Delay ms 200 FLASH Read Words F ADDRESS dat buff 32 demonstration of reading 64 bytes for i 0 i 32 itt PORTD dat buff i output low byte to PORTD PORTB dat buff i gt gt 8 output higher byte to PORTB Delay 5 200 MIKROELEKTRONIKA SOFTWARE AND H
160. 0 if CF card was detected and successfully initialized 1 if FAT16 boot sector was not found 255 if card was not detected 2045 Initializes CF card reads CF 16 boot sector and extracts necessary data Description needed by the library Requires Nothing Init the FAT library if Cf Fat Init Init the FAT library Cf_Fat_QuickFormat Prototype unsigned char Cf Fat QuickFormat char cf fat label 0 if CF card was detected successfully formated and initialized 1 if FAT16 format was unseccessful 255 if card was not detected Formats to FAT16 and initializes CF card Parameters cf fat label volume label 11 characters in length If less than 11 characters are provided the label will be padded with spaces If null Description string is passed the volume will not be labeled Note This routine can be used instead or in conjunction with Cf Fat Init routine Note If CF card already contains a valid boot sector it will remain unchanged except volume label field and only FAT and ROOT tables will be erased Also the new volume label will be set format and initialize the FAT library if Cf Fat QuickFormat amp cf fat label MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 259 CHAPTER 6 Libraries mikroC PRO for AVR Cf_Fat_Assign Prototype unsigned short Cf Fat Assign char filename char file cre attr Returns 0 if file doe
161. 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 Requires Glcd needs to be initialized see Glcd Init routine Draw a vertical line between dots 10 5 and 10 25 Glod V Line 5 25 10 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 289 CHAPTER 6 Libraries mikroC PRO for AVR Glcd H Line void Glcd H Line unsigned short x start unsigned short x end unsigned short y pos unsigned short color Nothing Draws a horizontal line on Glcd Prototype Parameters x start X coordinate of the line start Valid values 0 127 Description x end X coordinate of the line end Valid values 0 127 y pos y coordinate of horizontal line Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the line color 0 white 1 black and 2 inverts each dot Glcd needs to be initialized see Glcd Init routine Draw a horizontal line between dots 10 20 and 50 20 Gled H Line 10 50 20 1 Glcd Rectangle void Glcd Rectangle unsigned short x upper left unsigned short Prototype y upper left unsigned short x bottom right unsigned short y bottom right unsigned short color Draws a rectangle on Glcd Parameters x upper left coordinate of the upper left rectangle comer Valid values 0
162. 1 SPI Glcd Box void SPI Glcd Box char x upper left char y upper left char X bottom right char y bottom right char color Draws a box on Glcd Parameters x upper left X coordinate of the upper left box corner Valid values 0 127 y upper left y coordinate of the upper left box corner Valid values 0 63 x bottom right X coordinate of the lower right box corner Valid values 0 127 y bottom right y coordinate of the lower right box corner Valid values 0 63 color color parameter Valid values 0 2 Description The parameter color determines the color of the box fill O white 1 black and 2 inverts each dot Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Draw a box between dots 5 15 and 20 40 SPI Glcd Box 5 15 20 40 1 460 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI Glcd Circle void SPI Glcd Circle int x center int y center int radius char color Nothing Draws a circle on Glcd Prototype Parameters x center X coordinate of the circle center Valid values 0 127 Description y center y coordinate of the circle center Valid values 0 63 radius radius size color color parameter Valid values 0 2 The parameter color determines the color of the circle line 0 white 1 black and 2 inverts each dot Glcd needs to be initialized f
163. 10 different shortcuts by editing ToolO Tool9 Options ze File Name Parameters Macro Tr Shortcut F11 Tool Name 10 YeHEX_FILE_NAME Clear all fields OK Tools v Insert Cancel MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 67 CHAPTER 2 Environment mikroC PRO for AVR Output settings By modifying Output Settings user can configure the content of the output files You can enable or disable for example generation of ASM and List file Also user can choose optimization level and compiler specific settings which include case sensitivity dynamic link for string literals setting described in mikroC PRO for AVR specifics Build all files as library enables user to use compiled library mcl on any AVR MCU Output Settings 68 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR 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 meaning described below A series of characters matches th
164. 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 text 7 temp fraction 10 48 Extract ones digit print temperature on LCD Lcd Out 2 5 text void main Led Initialize LCD Lcd Cmd LCD CLEAR Clear LCD Lcd Cmd LCD CURSOR OFF Turn cursor off Lcd Out 1 1 Temperature Print degree character C for Centigrades Led Chr 2 13 223 Hed Ghr 2 14 C main loop do perform temperature reading Ow Reset Onewire reset signal Ow Write O0xCC Issue command SKIP ROM Ow Write 0x44 Issue command CONVERT T Delay us 120 Ow Reset Ow Write 0xCC Issue command SKIP ROM Ow Write OxBE Issue command READ SCRATCHPAD temp Ow Read temp Ow Read lt lt 8 temp MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 351 mikroC PRO for AVR CHAPTER 6 Libraries Format and display result on Lcd Display Temperature temp Delay ms 500 while 1 125 C HW Connection Q 2 o ill VCC OSCILLATOR 9LVOJNWNLV LCD 2X16 Example of DS1820 connection 352 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries PORT EXPANDER
165. 123 12 d 1 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 PRO for AVR Environment MIKROC PRO FOR AVR COMMAND LINE OPTIONS Usage mikroCAvr exe lt opts gt opts lt infile gt lt opts gt lt opts gt Infile can be of c and pld_ type The following parameters and some more see manual are valid P MCU for which compilation will be done FO Set oscillator in MHz SP Add directory to the search path list IP Add directory to the include search list N Output files generated to file path specified by filename B Save compiled binary files c1 to directory o Miscellaneous output options pBG Generate debug info L Check and rebuild new libraries DL Build all files as libraries Y Dynamic link for string literals C Turn on case sensitivity Example mikrocAvr exe MSF DBG pATMEGA16 ES C 011111114 fo8 N C NVLcdNLcd mcpav SP C Program Files Mikroelektronika mikroC PRO for AVR Defs SP C Program Files Mikroelektronika mikroc PRO for AVR Uses LTE64KW SP C Led Led c Lib Math mcl Lib MathDouble mcl Lib System mcl Lib Delays mcl Lib LcdConsts mcl Lib Lcd mcl Parameters used in the example MSF Short Message Format used for internal purposes by IDE pBG
166. 2 declare variables ol and 2 of Circle MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 165 CHAPTER 5 Language Reference mikroC PRO for AVR 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 it a comma delimited sequence of values within braces similar to array For example Referring to declarations from th xample above Declare and initialize dots p and q struct Dot p l 1 2 13 7 0 5 Declare and initialize circle ol struct Circle 1 1 0 0 radius is 1 center is at 0 0 Incomplete Declarations Incomplete declarations are also known as forward declarations A pointer to a structure type A can legally appear in the declaration of another structure before has been declared struct A incomplete struct B struct A pa struct A struct B pb The first appearance of A is called incomplete because there is no definition for it at that point An incomplete declaration is allowed here because the definition of B doesn t need the size of 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 struc
167. 3 Time ys Lcd Chr 2 E Led Chr 2 tys Lcd Out 1 12 200 f Main procedure void main Init Main Perform initialization while 1 Endless loop Read Time Read time from RTC PCF8583 Transform Time Format date and time Display Time Prepare and display on LCD Delay_ms 1000 Wait 1 second MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 409 CHAPTER 6 Libraries mikroC PRO for AVR SOFTWARE SPI LIBRARY The mikroC PRO for AVR provides routines for implementing Software SPI commu nication 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 variables must be defined in all projects using Software SPI Library extern sfr sbit Chip select line sbit Chip Select at Chip Select i PORTB BO extern sfr sbit Data In line sbit SoftSpi SDI at SoftSpi SDI PINB B6 extern sfr sbit sbit
168. 5 1 Read dummyl Description Writes byte via the SPI bus Parameters wrdata data to be sent SPI module must be initialized before using this function See SPI1 Init and SPI1_Init_Advanced routines write a byte to the SPI bus char buffer SPIL Write buffer 428 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries 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 DAC module connections sbit Chip Select at PORTB BO sbit Chip Select Direction at DDRB BO End DAC module connections unsigned int value void InitMain DDAO 0 Set PAO pin as input DDA1 0 Set 1 pin as input Chip Select 1 Deselect DAC Chip Select Direction 1 Set CS pin as Output SPIL Init Initialize SPI1 module 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 SPIl Write temp Send high byte via SPI Send Low Byte temp valueDAC Store valueDAC 7 0 to temp 7 0 SPI1 Write temp Send low byte via SPI Chip Select 1
169. 5 Language Reference mikroC PRO for AVR 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 is checked before the first entry into the block statement is executed repeatedly until the value of condition expressionis false After each iteration of the loop increment expression increments a loop counter Conse quently 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 for statement The only way to break out of this loop is by means of the break statement Here is an example of calculating scalar product of two vectors using the for statement for S 0 0 3 ong asso mc ana Bays There is another way to do this for S 0 i 0 E lt n api bial itt 92 valid but ugly but it is considered a bad programming style Although legal calculating the sum should not be a part of the incrementing expression because it is not in the service of loop routine Note that null statement is used for the loop body 214 MIKROELEKTRON
170. 5 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 TWI Library UART Library 228 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Standard ANSI C Libraries 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 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 Glcd uses Glcd_Fonts and Port Expander library which uses SPI library This means that if you check SPI Gled library in Library manager all libraries on which it depends will be checked too MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 229 CHAPTER 6 Libraries mikroC PRO for AVR CANSPI SPI Gicd_Fonts it USART PetExpander 88i 7 EN sPLLcd i mum Gom Jey Spmi J T6963C Trigon Related topics Library manager A
171. 57 StSt Gee tac ae ah too ee tae 558 is eek s dw ae k RS a ERE ee a 558 TM 558 STERF cus cR RUE KES CORRI ON RU e Rt D RUN 558 Button Library 2 22 5252 e UR phate BRA ATE 559 External dependecies of Button Library 559 Library Routinies x cosa apes mee Us meus kd c ES 559 con ECT 560 Conversions 561 Library RoutineS 561 Byle TOS iode dri dede hne 562 Short IOS 7 5 cu ese eR Ree RR 562 noi e i i RERUM EE ERR ERR RERO RA 563 iusque RO Ob sain Gi ege UR a RR CRUS 563 Long OSI 222552 bebe vedete ege ts 564 LongWordToStr sene re lm rae Re ux Rc arn HR RA d 564 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Table of Contents FloatIoStr nne ca Rha ed be eee X e d e des 565 De6c2BO0 px pa toa EUR Re pace ALI De RUP e na a 566 Bed2DeC16 gt RE RR ERN MUCH MR EUN GR ERA B en a OG 566 Dec2Bcd16 d d e Need en 567 Sprint LIDA ru RE WERE IE RR Ead eas 568 FUNCIONS x ses esee e REA RR RO ACH RA 568 ios RR RET Aaa ie 568 SPAMU
172. 62 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment 7 Segment Display Decoder The 7 Segment Display Decoder is a convenient visual panel which returns deci mal hex value for any viable combination you would like to display on 7seg Click on the parts of 7 segment image to get the requested value in the edit boxes You can launch it from the drop down menu Tools 7 Segment Decoderor by clicking the Seven Segment Icon Ei from Tools toolbar MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 63 CHAPTER 2 Environment mikroC PRO for AVR UDP Terminal The mikroC PRO for AVR includes the UDP Terminal You can launch it from the drop down menu Tools UDP Terminal IP Address 192 168 20 25 Port 10001 Send mikroElektronika Send Append Send as typing LF Send as number mikroElektronika Receive 6 ASCII 64 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment Graphic LCD Bitmap Editor The mikroC PRO for AVR includes the Graphic LCD Bitmap Editor Output is the mikroC PRO for AVR compatible code You can launch it from the drop down menu Tools GLCD Bitmap Editor mikroElektronika Graphic LCD Bitmap generator fKSOT08 16963 Nokia3110 File loaded truck bmp P
173. 63C Sprite unsigned char px unsigned char py const Prototype 2 code char pic unsigned char sx unsigned char sy Fills graphic rectangle area px py to px sx py sy with custom size picture Parameters px X coordinate of the upper left picture corner Valid values multiples of the font width Description py y coordinate of the upper left picture corner pic picture to be displayed sx picture width Valid values multiples of the font width sy picture height 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 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example SPI T6963C Sprite 76 4 einstein 88 119 draw a sprite MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 493 CHAPTER 6 Libraries mikroC PRO for AVR SPI T6963C Set Cursor Prototype void SPI T6963C Set Cursor unsigned char x unsigned char y Sets cursor to row x and column y mS Parameters Description x Cursor position row number y Cursor position column number Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Exon e _T6963C Set Cursor cposx cposy SPI T6963C ClearBit Prototype SPI T6963C ClearBit char Clears control port bit s Parameters Description b bit mask The function will clear bit
174. 63C graphics 0 T6963C text 1 Delay ms 300 PB3 is pressed wa else if PINB3 T6963C graphics 1 T6963C text 1 Delay ms 300 4 is pressed else if PINB4 CUI Sd 7 if curs 3 curs switch curs case 0 no cursor break case 1 break case 2 break Delay ms 300 mikroC PRO for AVR display only text panel display text and graphic panels change cursor 0 T6963C cursor 0 blinking cursor T6963C cursor 1 T6963C cursor blink 1 non blinking cursor T6963C cursor 1 T6963C cursor blink 0 Move cursor even if not visible SA Cposxtt if cposx T6963C txtCols 1 cposx 0 cposytt if cposy T6963C grHeight T6963C CHARACTER HEIGHT cposy 0 T6963C set cursor cposx cposy Delay ms 100 528 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries HW Connection ILVOANLV i Toshiba T6963C Graphic LCD 240x128 50R Contrast Adjustment T6963C GLCD HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 529 CHAPTER 6 Libraries mikroC PRO for AVR TWI LIBRARY TWI full master MSSP module is available with a number of AVR MCU models mikroC PRO for AVR provides library which supports the master TWI mode Note
175. 6963C Init routine enable cursor blinking T6963C Cursor Blink 1 524 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Library Example CHAPTER 6 Libraries The following drawing demo tests advanced routines of the T6963C GLCD library Hardware configurations in this example are made for the T6963C 240x128 display EasyAVR5 board and ATMEGA16 include T6963C h T6963C module connections char T6963C ctrlPort at FORTC char T6963C dataPort at PORTD char T6963C ctrlPort Direction at DDRC char T6963C dataPort Direction at DDRD sbit T6963C ctrlwr at PORTC B2 sbit T6963C ctrlrd at PORTC B1 sbit T6963C ctrlcd at PORTC BO sbit T6963C ctrlrst at PORTC B4 sbit T6963C ctrlwr Direction at DDRC B2 sbit T6963C ctrlrd Direction at DDRC B1 sbit T6963C ctrlcd Direction at DDRC B0 sbit T6963C ctrlrst Direction at DDRC B4 Signals not used by library they are set in main function sbit T6963C ctrlce at PORTC B3 sbit T6963C ctrlfs at PORTC B6 sbit T6963C ctrlmd at PORTC B5 sbit T6963C ctrlce Direction at DDRC B3 sbit T6963C ctrlfs Direction at DDRC B6 Sbit T6963C ctrlmd Direction at DDRC B5 End T6963C module connections bitmap pictures stored in ROM const code char mikroE 240x128 bmp const code char einstein void main char txtl1 EINSTEIN WOULD HAVE LIKED mE char
176. 7 Description The function will always produce the same sequence of numbers unless srand is called to seed the start point srand Prototype void srand unsigned Function uses x as a starting point for a new sequence of pseudo random num Description bers to be returned by subsequent calls to rand No values are returned by this function 552 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries xtoi Prototype unsigned xtoi register char s Function converts the input string s consisting of hexadecimal digits into an inte ger value The input parameter s should consist exclusively of hexadecimal dig Description its with an optional whitespace and a sign at the beginning The string will be processed one character at a time until the function reaches a character which it doesn t recognize including a null character Div Structures typedef struct divstruct int quot int rem div t typedef struct ldivstruct long quot long rem p typedef struct uldivstruct unsigned long quot unsigned long rem uldiv t MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 553 CHAPTER 6 Libraries mikroC PRO for AVR ANSI C STRING LIBRARY The mikroC PRO for AVR provides a set of standard ANSI C library functions use ful for manipulating strings and RAM memory Note Not all of the standard functions h
177. 7 txt is 123 4567 Ext is 374 2 FloatToStr ff3 txt txt is 1 234e 6 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 565 CHAPTER 6 Libraries mikroC PRO for AVR Dec2Bcd Prototype unsigned short Dec2Bcd unsigned short decnum Returns Converted BCD value Converts input unsigned short integer number to its appropriate BCD represen tation Description Parameters decnum unsigned short integer number to be converted unsigned short a b 22 Dec2Bcd a b equals 34 Bcd2Dec16 Prototype unsigned Bcd2Decl16 unsigned bcdnum Converted decimal value Converts 16 bit BCD numeral to its decimal equivalent Description Parameters bcdnum 16 bit BCD numeral to be converted unsigned b 0x1234 a equals 4660 Bcd2Dec16 a b equals 1234 566 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Dec2Bcd16 Returns Converted BCD value Converts unsigned 16 bit decimal value to its BCD equivalent Description Parameters decnum unsigned 16 bit decimal number to be converted unsigned a b 2345 Dec2Bcd16 a b equals 9029 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 567 CHAPTER 6 Libraries mikroC PRO for AVR SPRINT LIBRARY The mikroC PRO for AVR provides the standard ANSI C Sprintf function for easy data formatting
178. 92 Write 293 Write Text 294 Gled Image 2 2444 ide be ER Eee E ue eee edes 295 Library 295 HW Connection sorsara ee eu es 298 Keypad Library ole uc dade bra 299 External dependencies of Keypad 299 Library Routines 222522222163 Sa eb ae bee Y 299 Keypad Init 300 _ _ 301 _ _ 301 Library Example 2 sss n he 301 HW Connection 2222 22 nga d PX debe ed d edid 304 Lcd LIDrapy us Go ices wR dw ueni remix denk a Rudy denk d Rud eara ar e aw qs 305 External dependencies of Lcd 305 Library RoutineS 306 En So ang Pate eeu ae ee ates oe ee dee te ee ele 307 Lcd Out uus ne ye kena 308 Led Out Cp sek eR ERROR ERREUR XR EROR aes 308 Lcd CAP oeae renes Lib DEP tbe Ee he EE De ae be 314 309 Led Chr C 309 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XVII Table of Contents mikroC PRO for AVR
179. 99 SPI T6963C 499 SPI T6963C Cursor 500 Library Example coron ees er REC d s 500 HW Connection 505 T6963C Graphic LCD Library 506 XXIV MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Table of Contents External dependencies of T6963C Graphic LCD Library 507 Library Routines 508 T6963C Init nter E PHS COM ae WE e EROR dx 509 T6963C WriteData 510 T6963C WriteCommand 511 769636 sic a tah hone eae ean Ra sse AES RS 511 T6963C WaitReady 511 TO963C Fill t Rete ERR RT alk Bias I Pee eds 512 T6963C Dot vi uer ERR ada UU Ja HI en ADR S 512 T6963C Write 513 6963 _ _ 514 T6963C Line 15 T6963C Rectangle 515 T6963C BOK ie puedes Pere eee 516 T6963G Girdle cis cause cce RR xci De Tut RC RT a eR 516 T6963C Image sie ee ee 517 6963
180. A SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Selects the inverted PWM 16bit mode Selects the normal non inverted PWM 16bit mode TIRRI Selects the Timer Counter1 used with eiiis PWM 16bit_Start and PWM16bit Stop Selects the Timer Counter3 used with PWM 16bit Start and PWM16bit Stop Selects the channel Timer Counter1 cid used with PWM16bit Change Duty Selects the channel B on Timer Counter1 used with PWM16bit Change Duty Selects the channel C on Timer Counter1 used with PWM16bit Change Duty Selects the channel A on Timer Counter3 used with PWM16bit Change Duty Selects the channel B on Timer Counter3 used with PWM16bit Change Duty Selects the channel C on Timer Counter3 used with PWM16bit Change Duty WM16 PWM16 INVERTED TIMER3 TIMI Note Not all of the MCUs have 16bit PWM and not all of the MCUs have both Timer Counter1 and Timer Counter3 Sometimes like its the case with ATmega168 MCU has only Timer Counter1 and channels A and B Therefore constants that have in their name Timer3 or channel C are invalid for ATmega168 and will not be visi ble from Code Assistant It is highly advisable to use this feature since it handles all the constants available and eliminates any chance of typing error MIKROELEKTRONIKA SO
181. ANSPI MODE CONFIG OxFF set CONFIGURA TION mode CANSPISetMask CANSPI MASK Bl 1 CANSPI CONFIG XTD MSG set all maski bits to ones CANSPISetMask CANSPI MASK B2 1 CANSPI CONFIG XTD MSG set all mask2 bits to ones MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 249 CHAPTER 6 Libraries mikroC PRO for AVR CANSPISetFilter CANSPI FILTER B2 F3 12111 CANSPI CONFIG XTD MSG set id of filter B1 F1 to 3 CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode Tx ID 3 set tx ID while 1 endless loop Msg Rcvd CANSPIRead amp Rx ID RxTx Data amp Rx Data Len amp Can Rcv Flags receive message if Rx ID 12111u amp amp Msg Revd if message received check id PORTC RxTx Data 0 id correct output data at PORTC RxTx Data 0 increment received data CANSPIWrite Tx ID RxTx Data 1 Can Send Flags send incre mented data back HW Connection VCC o 100K VCC i 18 TX Vdd nje LP RX RST CLKO CS 50 SI TX2 SCK OSC2 INT OSC1 RXOB w ilm l karel kor 1 lI 8 MHz VCCo OSCILLATOR MCP2510 Vss RX1B s 10R gt n oo A o 1 LL
182. APTER 6 Libraries mikroC PRO for AVR Library Routines Lcd Init Lcd Out Lcd Out Cp Lcd Chr Lcd Chr Cp Lcd Cmd 306 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Lcd Init Prototype Initializes Lcd module Global variables LC Data bit 7 LC Data bit 6 LCD_D5 Data bit 5 LC Data bit 4 L Register Select data instruction signal pin EN Enable signal pin Requires LC Direction Direction of the Data 7 pin LCD D6 Direction Direction of the Data 6 pin LCD D5 Direction Direction of the Data 5 pin LCD D4 Direction Direction of the Data 4 pin LCD RS Direction Direction of the Register Select pin CD EN Direction Direction of the Enable signal pin must be defined before using this function Lcd pinout settings sbit LCD RS at PORTD B2 sbit LCD EN at PORTD B3 sbit LCD D7 at PORTD B4 sbit LCD D6 at PORTD B5 sbit LCD D5 at PORTD B6 sbit LCD D4 at PORTD B7 Pin direction sbit LCD RS Direction sbit LCD EN Direction sbit LCD D7 Direction sbit LCD D6 Direction sbit LCD D5 Direction sbit LCD D4 Direction Lcd Init MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 307 CHAPTER 6 Libraries mikroC PRO for AVR Lcd Out Prototype Lcd Out char row char column char text Prints text on Lcd starting from specified position Both string variables and lit
183. ARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Keypad_Key_Press Prototype Keypad Key Press void The code of a pressed key 1 16 If no key is pressed returns 0 Reads the key from keypad when key gets pressed Port needs to be initialized for working with the Keypad library see Keypad Init char kp kp Keypad Key Press Keypad Key Click Prototype char Keypad Key Click void The code of a clicked key 1 16 If no key is clicked returns 0 Call to Keypad Key Click is a blocking call the function waits until some key is pressed and released When released the function returns 1 to 16 depending Description on the key If more than one key is pressed simultaneously the function will wait until all pressed keys are released After that the function will return the code of the first pressed key Port needs to be initialized for working with the Keypad library see Keypad Init char kp kp Keypad Key Click 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 is transformed into ASCII codes 0 9 A F and displayed on LCD In addition a small single byte counter displays in the second LCD row number of key presses MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS
184. ARDWARE SOLUTIONS FOR EMBEDDED WORLD 281 CHAPTER 6 Libraries mikroC PRO for AVR GRAPHIC LCD LIBRARY The mikroC PRO for AVR 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 Description using Graphic LCD Library extern sfr char char GLCD DataPort at extern sfr char Direction of the Glcd char f GLCD DataPort Directio LCD D P D 3 GLCD DataPort Direction Data Port n at DDRC exterm sfr sbie erco csi Chip Select 1 line 292 257 05 ae extern str sbit Chip Select Qing l ose te Register select line ar i LC iC LC 3 LCD RW extern sfr sbit GLCD RW Read Write line iuis um ar extern sfr sbit GLCD EN Enable line 1 LCD RST at extern sfr sbit GLCD RST Reset line PORTD B7 extern sfr sbit Direction of the Chip sbit LCD CS1 Direction GLCD CS1 Direction Select 1 pin at D B2 extern sfr sbit Direction of the Chip sbit LCD CS2 Direction D CS2 Direction Select 2 pin at D B3 C C x GL x GL i extern sfr sbit Direction of the sbit GLCD RW Direction GLCD_RW_Direction Read Write pin at D 5 extern sfr sbit Direction of the i CD EN Direction GLCD EN Direction Enable pin extern sfr sb
185. AS XORed with 1 IT WAS EQUAL TO STOP BYTE 0 ADDRESS UNCHANGED bit5 0 FIXED bit4 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 DATA1 if exists WAS XORed with 1 IT START BYTE or STOP BYTE 0 DATA1 if exists UNCHANGED bitlbitO 0 to 3 NUMBER OF DATA BYTES SEND CRC generation crc send datalen address crc send data 01 if exists crc send data 1 if exists crc send data 2 if exists send ore send if crc send START BYTE cre send crc_sendt NOTE DATALENK lt 4 0 gt can not take the STOP_BYTE lt 4 0 gt values MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD STOP BYT START BYTE 4 0 Fl CHAPTER 6 Libraries START BYTE or WAS EQUAL TO WAS EQUAL TO WAS EQUAL TO QUE 401 CHAPTER 6 Libraries mikroC PRO for AVR Software lC Library The mikroC PRO for AVR provides routines for implementing Software 1 commu nication These routines are hardware independent and can be used with any MCU The Software 1 library enables you to use MCU as Master communication Multi master mode is not supported Note This library implements time based activities so interrupts need to be dis abled when using Software 1 No
186. AVR ALU which performs arithmetic operations is opti mized for working with bytes Although mikroC PRO is capable of handling very complex data types AVR may choke on them especially if you are working on some of the older models This can dramatically increase the time needed for performing even simple oper ations Universal advice is to use the smallest possible type in every situation It applies to all programming in general and doubly so with microcontrollers Types efficiency is determined by the part of RAM memory that is used to store a variable constant 113 CHAPTER 4 AVR Specifics mikroC PRO for AVR Nested Calls Limitations There are no Nested Calls Limitations except by RAM size A Nested call repre sents a function call to another function within the function body With each function call the stack increases for the size of the returned address Number of nested calls is equel to the capacity of RAM which is left out after allocation of all variables Important notes There are many different types of derivates so it is necessary to be famil iar with characteristics and special features of the microcontroller in you are using Some of the AVR MCUs have hardware multiplier Due to this be sure to pay attention when porting code from one MCU to another because com piled code can vary by its size Not all microcontrollers share the same instruction set It is advisable to carefully read the instruction set of
187. AVR provides a library for communication with Lcd with HD44780 compliant controllers in 8 bit mode via SPI interface For creating a custom set of Lcd characters use Lcd Custom Character Tool Note Library uses the SPI module for communication The user must 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 Prior to calling any of this library routines Spi Rd Ptr needs to be initialized with the appropriate SPI Read routine External dependencies are the same as Port Expander Library external dependen cies Library Routines SPI Lcd8 Config SPI Out SPI Lcd8 Out Cp SPI Lcd8 Chr SPI Lcd8 Chr Cp SPI Lcd8 Cmd 476 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI Lcd8 Config Prototype SPI Lcd8 Config char DeviceAddress Nothing Initializes the Lcd module via SPI interface Parameters Description DeviceAddress SPI expander hardware address see schematic at the bottom of this page Global variables SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip
188. 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 pre viously declared myunsigned like this This example writes low byte of bit field of myunsigned type to PORTO myunsigned Value For PORTO void main Value For PORTO lo nibble 7 Value For PORTO hi nibble 0 0 PO char void amp Value For PORTO typecasting 1 address of structure to pointer to void 2 pointer to void to pointer to char 3 dereferencing to obtain the value MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 173 CHAPTER 5 Language Reference mikroC PRO for AVR TYPES CONVERSIONS The mikroC PRO for AVR is a strictly typed language with each operator statement and function demanding appropriately typed operands arguments However we often have to use objects of mismatching types in expressions In that case type conversion is needed Conversion of object of one type means that object s type is changed into another type The mikroC PRO for AVR 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 lan guage definition and we use an expression of diff
189. Build All Icon 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 PRO for AVR will generate output files Output Files Upon successful compilation the mikroC PRO for AVR will generate output files in the project folder folder which contains the project file mcpav Output files are summarized in the table below Intel HEX Intel style hex records Use this file to program AVR p MCU Binary mikro Compiled Library Binary distribution of appli n cation that can be included in other projects x Overview of AVR memory allotment instruction List File lst addresses registers routines and labels Human readable assembly with symbolic names Assembler File asm extracted from the List File Assembly View After compiling the program in the mikroC PRO for AVR you can click the View Assembly icon or select Project View Assembly from the drop down menu to review the generated assembly code asm file in a new tab window Assembly is human readable with symbolic names Related topics Project Menu Project Toolbar Error Window Project Manager Pro ject Settings 86 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment ERROR MESSAGES Compiler Error Messages Syntax Error ss
190. CC og 7 ewe Lo Row 16 Seo 2008 135826 mikroC PRO for AVR IDE Features mikroC PRO for AVR allows you to quickly develop and deploy complex applica tions Write your C source code using the built in Code Editor Code and Parameter Assis tants Code Folding Syntax Highlighting Auto Correct Code Templates and more Use included mikroC PRO for AVR libraries to dramatically speed up the devel opment data acquisition memory displays conversions communication etc Monitor your program structure variables and functions in the Code Explorer Generate commented human readable assembly and standard HEX compatible with all programmers Inspect program flow and debug executable logic with the integrated Software Simulator 2 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroC PRO for AVR Introduction Get detailed reports and graphs RAM and ROM map code statistics assembly listing calling tree and more mikroC PRO for AVR provides plenty of examples to expand develop and use as building bricks in your projects Copy them entirely if you deem fit that s why we included them with the compiler Where to Start In case that you re a beginner in programming AVR microcontrollers read care fully the AVR Specifics chapter It might give you some useful pointers on AVR constraints code portability and good progra
191. CHAPTER 5 Language Reference mikroC PRO for AVR Initialization 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 globals and static objects must be constants or constant expres sions The initializer for an automatic object can be any legal expression that eval uates 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 1 char s hello struct complex c 0 1 0 2 where complex is a structure float float For structures or unions with automatic storage duration the initializer must be one of the following An initializer list Asingle expression with compatible union or structure type In this case the initial value of the object is that of the expression For example struct dot int x int y m 30 40 For more information refer to Structures and Unions Also you can initialize arrays of character type with a literal string optionally enclosed in braces Each character in the string including the null terminator initial izes successive elements i
192. C_Config 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 Initalizes the Graphic Lcd controller Parameters width Width of the Glcd panel height height of the Glcd panel fntw font width DeviceAddress SPI expander hardware address see schematic at the bottom of this page wr Write signal pin on Glcd control port x read signal pin on Glcd control port cd command data signal pin on Glcd control port rst reset signal pin on Glcd control port Display RAM organization The library cuts RAM into panels a complete panel is one graphics panel fol lowed by a text panel see schematic below Description schematic MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 485 CHAPTER 6 Libraries Requires mikroC PRO for AVR Global variables SPExpanderCS Chip Select line SPExpanderRST Reset line SPExpanderRST Direction Direction of the Chip Select pin SPExpanderCS Direction Direction of the Reset pin 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 module connections sbit SPExpanderRST at PORTB BO sbit SPExpanderCS at PORTB B1 sbit SPExpanderRST Direction at DDRB B0 SPE
193. D 175 CHAPTER 5 Language Reference mikroC PRO for AVR After this any two values associated with an operator are either int including the long and unsigned modifiers or float equivalent with double and long double in the mikroC PRO for AVR 1 If either operand is float the other operand is converted to float 2 Otherwise if either operand is unsigned long the other operand is con verted to unsigned long 3 Otherwise if either operand is long then the other operand is converted to 1ong 4 Otherwise if either operand is unsigned then the other operand is con verted 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 Ww qud 2 3 12 5 1 5 4 3 5 4 3 1 3 1 3 3 3 5 4 2 8 5 4 3 5 4 15 4 15 4 3 75 Pointer Conversions Pointer types can be converted to other pointer types using the typecasting mecha nism char Ink apy str char ip More generally the cast type will convert a pointer to type pointer to type 176 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference EXPLICIT TYPES CONVERSIONS TYPECASTING In most situations compiler will provide an automatic implicit conversion of types where needed without any user s interfer
194. D is connected to PORTB 1 or PORTB 2 you can observe the gradual change of emitted light This example is written for ATmega168 This AVR MCU has only Timer Counter1 split over two channels A and B In this example we are chang ing the duty ratio on both of these channels char current duty char current dutyl void main DDCO bit 0 Set PORTC pin 0 as input DDC1 bit 0 Set PORTC pin 1 as input DDC2 bit 0 Set PORTC pin 2 as input DDC3 bit 0 Set PORTC pin 3 as input current duty 255 initial value for current duty current dutyl 255 initial value for current duty DDRB B1 1 Set PORTB pin 1 as output pin for the PW according to datasheet DDRB B2 1 Set PORTB pin 2 as output pin for the PW according to datasheet PWMl6bit Init PWM16 FAST MODE 9BIT 16 PRESCALER 16bit 1 PWM16 INVERTED 255 1 do if PINC BO Detect if PORTC pin 0 is pressed Delay ms 40 Small delay to avoid deboucing effect current dutytt Increment duty ratio PWM16bit Change Duty current duty CH A Set incremented duty else if PINC B1 Detect if PORTC pin 1 is pressed Delay ms 40 Small delay to avoid deboucing effect current duty Decrement duty ratio PWMl6bit Change Duty current duty CH A Set decremented duty ratio else if PINC B2 1 Detect if PORTC pin 2 is pressed Delay ms 40
195. DDED WORLD CHAPTER 2 mikroC PRO for AVR Environment ASCII Chart The ASCII Chart is a handy tool particularly useful when working with LCD display You can launch it from the drop down menu Tools ASCII chart or by clicking the View ASCII Chart Icon 9 from Tools toolbar al NUL SOH STX ETX EOT ENQ ACK BEL BS LF 0 1 2 3 4 5 6 2 8 9 10 11 DLE DC1 DC2 DC3 DC4 SYN ETB EM SUB ESC 16 17 19 20 21 22 23 24 26 27 SPC a at 3271 33 35 36 37 38 39 40 42 43 ola 314151617 8 2 s 49 51 52 1353 54 55 56 59 67 68 69 72 B1 pu x 83 99 5 we f OA Cc lt A m O m N e e e eS m os U lt N N N N N N N 8 YV A X 5 e N RTS MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 61 CHAPTER 2 Environment mikroC PRO for AVR EEPROM Editor The EEPROM Editor is used for manipulating MCU s EEPROM memory You launch it from the drop down menu Tools EEPROM Editor When Use this EEPROM definition is checked compiler will generate Intel hex file project name ihex that contains data from EEPROM editor When you run mikroElektronika programmer software from mikroC PRO for AVR IDE project name hex file will be loaded automatically while inex file must be loaded manually mikroElektronika EE
196. Directi sbit rst Direct Description T6963C Data Port T6963C Control Port Direction of the T6963C Data Port Direction of the T6963C Control Port Write signal Read signal Command Data signal Reset signal wa Direction of the Write pin Direction of the Read pin Direction of the Data pin Direction of the Reset pin unsigned char sfr T6963C dataPort at PORTD unsigned char sfr T6963C ctrlPort at PORTC unsigned char sfr T6963C dataPort Direc tion at DDRD unsigned char sfr T6963C ctrlPort Direc tion at DDRC sbit T6963C ctrlwr at 20 it T6963C ctrlrd at 5 Bl it T6963C ctrlcd at it T6963C ctrlrst PORTC B4 lwr Directi B23 lrd Directs Jis lcd Directi B0 sbit T6963C ion at ctrlrst Direct DDRC B4 507 CHAPTER 6 Libraries mikroC PRO for AVR Library Routines T6963C_Init T6963C_WriteData T6963C_WriteCommand T6963C_SetPtr T6963C_WaitReady T6963C_Fill T6963C_Dot T6963C_Write_Char T6963C_Write_Text T6963C_Line T6963C_Rectangle T6963C_Box T6963C_Circle T6963C_Image T6963C_ Sprite T6963C_Set_Cursor Note The following low level library routines are implemented as macros These macros be found in the r6963c n header file which is located in the T6963C example projects folders T6963C ClearBit T6963C SetBit T6963C NegBit T6963C DisplayGrPanel T6963C Di
197. E AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries HW Connection LDO ae 330 CJ LD1 ae 330 LD2 330 L 330 gt LD4 330 LD5 330 060 Vcc o ITI LD6 do 330 OSCILLATOR 3 NEM 9 330 ADC HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 233 CHAPTER 6 Libraries mikroC PRO for AVR CANSPI LIBRARY The SPI module is available with a number of the AVR compliant MCUs The mikroC PRO for AVR 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 is 200Kbit s Cables used are shielded twisted pairs CAN supports two message formats Standard format with 11 identifier bits and Extended format with 29 identifier bits Note
198. E AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 521 CHAPTER 6 Libraries mikroC PRO for AVR T6963C_PanelFill Prototype 1T6963C_PanelFill unsigned char v Nothing Fill current panel in full graphict text with appropriate value 0 to clear Description Parameters v Value to fill panel with Requires Toshiba Toshiba GLCD module needs to be initialized See the T6963C_Init routine module needs to be initialized See the T6963C Init routine clear current Por EE T6963C PanelFill T6963C GrFill Prototype void T6963C GrFill unsigned char v Fill current graphic panel with appropriate value 0 to clear Description Parameters v Value to fill graphic panel with Toshiba GLCD module needs to be initialized See the T6963C Init routine clear current graphic panel 4 _GrFill 0 T6963C_TxtFill Prototype void 16963C_TxtFill unsigned char v Fill current text panel with appropriate value 0 to clear Description Parameters v this value increased by 32 will be used to fill text panel Toshiba GLCD module needs to be initialized See the T6963C Init routine clear current text panel T6963C TxtFill 0 522 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries T6963C_Cursor_Height Prototype void T6963C Cursor Height unsigned char n Set cursor size Description Parameters n cursor height
199. ELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD USER MANUAL Table of Contents CHAPTER 1 CHAPTER 2 CHAPTER 3 CHAPTER 4 CHAPTER 5 CHAPTER 6 Introduction mikroC PRO for AVR Environment mikroC PRO for AVR Specifics AVR Specifics mikroC PRO for AVR Language Reference mikroC PRO for AVR Libraries Table of Contents mikroC PRO for AVR CHAPTER 1 asain Roe Te 2 Where to Start 3 mikroElektronika Associates License Statement and Limited Warranty 4 IMPORTANT READ CAREFULLY 4 LIMITED 5 HIGH RISK ACTIVITIES 6 GENERAL PROVISIONS 6 Technical Support 7 How to Register 8 Who Gets the License Key 8 How to Get License Key 8 After Receving the License Key 10 CHAPTER 2 IDE OVERVIEW 12 Main Menu Options 13 File Menu Options 14 Edit Menu Options 15 Find TEX ae tars Sed ee a ee ee Oe ade a ek aed Beate SE ee 17 Replace Tex
200. EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries The next program tests MMC FAT routines First we create 5 different files in the root of MMC card and fill with some information Then we read the files and send them via UART for a check include lt built_in h gt sbit Mmc Chip Select at PORTG B1 sbit Mmc Chip Select Direction at DDRG B1 char fat txt 20 FAT16 not found file contents 50 XX MMC SD FAT16 library by Anton Rieckertn char filename 14 MIKROOOxTXT File names unsigned short tmp caracter loop loop2 unsigned long i size char Buffer 512 I I I Writes string to USART void I Write Str char ostr unsigned short i i 0 while ostr 1 UART1 Write ostr it UART1 Write 0x0A M M M Creates new file and writes some data to it void M Create New File filename 7 A Fat Assign amp filename 0xA0 Will not find file and then create file Mmc Fat Rewrite To clear file and start with new data for loop 1 loop lt 99 1 We want 5 files on the MMC card UARTI Write file contents 0 loop 10 48 file contents 1 loop 10 48 Mmc Fat Write file contents 42 write data to the assigned file MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 341 CHAPTER 6 Libraries mikroC PRO for AVR Creates many new
201. EMBEDDED WORLD 253 CHAPTER 6 Libraries mikroC PRO for AVR Cf_Init Initializes ports appropriately for communication with CF card Global variables Data Port Compact Flash data port RDY Ready signal line CF WE Write enable signal line CF OE Output enable signal line CF CDI Chip detect signal line CF_CE1 Enable signal line 2 Address pin 2 1 Address pin 1 CF A0 Address pin 0 CF Data Port direction Direction of the Compact Flash data direction port CF RDY direction Direction of the Ready pin CF WE direction Direction of the Write enable pin CF OE direction Direction of the Output enable pin CF CD1 direction Direction of the Chip detect pin 1 direction Direction of the Chip enable pin A2 direction Direction of the Address 2 pin 1 direction Direction of the Address 1 pin A0 direction Direction of the Address 0 pin must be defined before using this function 254 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Cf_Detect Prototype unsigned short Cf Detect void 1 if CF card was detected 0 otherwise Checks for presence of CF card by reading the chip detect pin MCU ports must be appropriately initialized for CF card See Wait until CF card is inserted do asm nop while Cf Detect Cf Enable
202. ER 5 mikroC PRO for AVR Language Reference signed short in E t unsigned short in 1 signed long int 2147483648 2147483647 unsigned long int 4 0 4294967295 Floating point Types The types float and double together with the long double variant are considered to be floating point types The mikroC PRO for AVR s implementation of an ANSI Standard considers all three to be the same type Floating point in the mikroC PRO for AVR is implemented using the Microchip AN575 32 bit format IEEE 754 compliant An overview of the floating point types is shown in the table below ee 1 5 1045 3 4 1038 1 5 1045 3 4 1038 i _ ili MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 151 CHAPTER 5 Language Reference mikroC PRO for AVR ENUMERATIONS An enumeration data type is used for representing an abstract discreet set of val ues with appropriate symbolic names Enumeration Declaration Enumeration is declared like this enum tag enumeration list Here tag is an optional name of the enumeration enumeration list is a comma delimited list of discreet values enumerators or enumeration constants Each enu merator is assigned a fixed integral value In the absence of explicit initializers the first enumerator is set to zero and the value of each succeeding enumerator is set to a value of its predec
203. ER ARITHMETIC Pointer arithmetic in the mikroC PRO for AVR is limited to assigning one pointer to another comparing two pointers comparing pointer to zero adding subtracting pointer and an integer value subtracting two pointers The internal arithmetic performed on pointers depends on the memory 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 PRO for AVR When the name of an array comes up in expression evaluation except with operators 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 161 CHAPTER 5 Language Reference mikroC PRO for AVR is defined as ad exp where either id is a pointer and exp is an integer or id is an integer and exp is a pointer The following statements are true amp a i ati a i a i According to these guidelines it can be written pa amp a 4 pa points to a 4 x 3 if a7 buts y pa 3 y a 4 3 Also the care should be taken when using operator precedence
204. Example This is a simple demonstration of CANSPI Library routines usage First node initi ates the communication with the second node by sending some data to its address The second node responds by sending back the data incremented by 1 First node then does the same and sends incremented data back to second node etc Code for the first CANSPI node unsigned char Can Init Flags Can Send Flags Can Rcv Flags can flags unsigned char Rx Data Len received data length in bytes char RxTx Datal 8 can rx tx data buffer char Msg Rcvd reception flag long Tx ID Rx ID can rx and tx ID CANSPI module connections sbit CanSpi CS at 0 sbit CanSpi CS Direction at DDRB B0 sbit CanSpi Rst at PORTB B2 sbit CanSpi Rst Direction at DDRB B2 End CANSPI module connections void main 0 ADCSRA B7 7 0 set AN pins to Digital I O PORTC 0 clear PORTC DDRC 255 Can Init Flags 0 Flags 0 clear flags Rev Flags 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 247 CHAPTER 6 Libraries Can Send Flags PRIORITY_0 amp CANSPI TX XTD FRAME amp Can Init Flags value to be used CANSPI CONFIG SA PLE THRICE amp mikroC PRO for AVR form value to be used Ly with CANSPIWrite CANSPI TX NO RTR FRAME form EG2 PRG ON amp with CANSPIInit
205. F dat 4 0 ensure that message received flag is 0 dat 5 0 ensure that error flag is 0 dat 6 0 RS485Master Send dat 1 160 SREG I 1 enable global interrupt RXCIE 1 enable interrupt on usart receive while 1 upon completed valid message receiving data 4 is set to 255 Cnet MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 397 CHAPTER 6 Libraries mikroC PRO for AVR if dati 51 1 if an error detected signal it PORTC dat 5 by setting PORTC if 4 if message received successfully cnt 0 dat 4 0 clear message received flag j dati 3 for 1 i lt dati 3 i show data on PORTB PORTB dat i 1 increment received dat 0 dat 0 dat 0 1 send back to Slave Delay ms 1 RS485Master Send dat 1 160 if cnt gt 100000 if in 100000 poll cycles the answer PORTA ZZ was not detected signal cnt 0 2 d failure of send message RS485Master Send dat 1 160 if PORTA gt 10 if sending failed 10 times PORTA 0 RS485Master Send dat 1 50 send message broad cast address RS485 Slave code char dat 9 buffer for receving sending messages char 1 1 sbit RS485 rxtx pin at PORTD B2 set transcieve pin sbit RS485 rxtx pin direction at DDRD B2 set transcieve pin direction Interrupt routine void interrupt org 0x16 RS485Slave_ Receive dat
206. FIG FLAGS is formed from predefined constants see CANSPI constants Global variables CanSpi CS Chip Select line CanSpi Rst Reset line CanSpi CS Bit Direction Direction of the Chip Select pin CanSpi Rst Bit Direction Direction of the Reset pin must be defined before using this function The CANSPI routines are supported only by MCUs with the SPI module The SPI module needs to be initialized See the Spi Init and Spi Init Advanced routines MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 237 CHAPTER 6 Libraries mikroC PRO for AVR CANSPI module connections sbit CanSpi CS at PORTB B0 sbit CanSpi CS Direction DDRB BO sbit CanSpi Rst at PORTB B2 sbit CanSpi Rst Direction at DDRB B2 End CANSPI module connections 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 form value to be used CAN CONFIG PHSEG2 PRG ON amp with CANSPIInitialize CAN CONFIG XTD MSG amp CAN CONFIG DBL BUFFER ON amp CAN CONFIG VALID XTD MSG Init initialize SPI module Spi Rd Ptr SPI1 Read pass pointer to SPI Read function of used SPI module CANSPIIn
207. FOR EMBEDDED WORLD 301 CHAPTER 6 Libraries mikroC PRO for AVR unsigned short kp char txt 6 ent oldstate Keypad module connections sfr char sfr char keypadPort at PORTB keypadPort Direction at DDRB End Keypad module connections LCD module connections sbit LCD RS sbit LC sbit LC sbit LC sbit LC sbit LC at at D4 at D5 at at D7 at Ij z sbit LCD sbit LCD sbit LCD D4 D D sbit LC sbit LC sbit LCD PORTD PORTD PORTD PORTD PORTD PORTD RS Direction EN Direction Direction D5 Direction D6 Direction D7 Direction B2 4 5 B6 B7 at at at at at at DDRD DDRD B3 DDRD B4 DDRD B5 DDRD B6 DDRD B7 B2 End LCD module connections void main cnt 0 Keypad Init Led Init BED i Lcd Out 1 1 Lcd Out 1 1 Lcd Out 2 1 do kp 0 Lcd Cmd LCD CLEAR Lcd Cmd LCD CURSOR OFF jw Key AT Times 0 Reset counter Initialize Keypad Initialize LCD Clear display Cursor off Write message text on LCD Reset key code variable Wait for key to be pressed and released do kp kp while switch switch kp kp case 10 for keypad4x3 case 11 case 12 default Keypad Key Press Keypad Key Click kp Prepare value for output kp 42 break kp 48 break kp
208. FTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Table of Contents Customizing Projects 2 2 2 4 80 Edit ProjGCt iie mmus sl ese ede Sea 80 Managing Project Group 80 Add Remove Files from 80 Project Level Defines 82 Source Flesh aces E WU PO eo 83 Managing Source Files 83 Creating new source file 83 Opening an existing 83 Printing an open 84 Saving baee bb es bead keds 84 Saving file under a different name 84 Closing file Sime wie gone Gee REDE a es 84 Clean Project Folder ped ba tbat bad 85 Clean Project Folder 85 Compilation 2o ahah TE ERU LER A dow Ob Re dC 86 Output Files 86 Assembly View 86 Error Messages uisus sek es e ge eoe eR RI Pe Rue d M RR RUE 87 Compiler Error Messages 87 Compiler Warning Messages 90 Linker Error Messages
209. FTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 383 CHAPTER 6 Libraries mikroC PRO for AVR PWM 16bit_Init Protot void PWM16bit Init unsigned short wave mode unsigned short prescaler unsigned short inverted unsigned short duty Initializes the PWM module Parameter wave mode is a desired PWM 16bit mode There are several modes included PWM Phase Correct 8 bit PWM Phase Correct 9 bit PWM Phase Correct 10 bit Fast PWM 8 bit Fast PWM 9 bit Fast PWM 10 bit Parameter prescaler chooses prescale value N 1 8 64 256 or 1024 some modules support 32 and 128 but for this you will need to check the datasheet for the desired MCU Paremeter inverted is for choosing between inverted and non inverted PWM signal Parameter duty sets duty ratio from 0 to TOP value this value varies on the PWM wave mode selected PWM signal graphs and formulas are shown below FAST f i o Description MOD E pwm 1 1 Duty Ratio W i re S py 3t Atem Stowe town 7t Non Inverted Inverted The N variable represents the prescaler factor 1 8 64 256 or 1024 384 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 Libraries fa i o Pem 2 N TOP TOP Duty Ratio AZ JA LS y y 3
210. Generate debug info pATMEGA16 MCU pATMEGA16 selected C Turn on case sensitivity 011111114 Miscellaneous output options fo8 Setoscillator frequency in MHz N C Led Lcd mcpav SP C Program Files Mikroelektronika mikroC PRO for AVR defs Output files generated to file path specif ied by filename SP C Program Files Mikroelektronika mikroC PRO for AVR defs Add directory to the search path list SP C Program Files Mikroelektronika mikroC PRO for AVR uses Add directory to the search path list SP C Led Add directory to the search path list Lcd c 11 Math mcl MathDouble mcl Lib System mcl Lib Delays mcl Lib LcdConsts mcl Lib Lcd mcl Specify input files MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 75 CHAPTER 2 Environment mikroC PRO for AVR TUTORIALS Projects The mikroC PRO for AVR organizes applications into projects consisting of a sin gle project file extension mcpav and one or more source files extension mikroC PRO for AVR IDE allows you to manage multiple projects see Project Manager Source files can be compiled only if they are part of a project The project file contains the following information project name and optional description target device device flags config word device clock list of the project source files with paths header files h binary files mcl
211. HTTP requests BR KK KK KK RK RK RK kk kk kk kk kkk kk kk kk ck ckck ck ck AK functions put the constant string pointed to by s to the ENC transmit buffer Sf unsigned int putConstString const code char s unsigned int ctr 0 while s Spi Ethernet putByte s ctrte o return ctr as 446 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries 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 def inition above the define line below should be commented out define putConstString SPI Ethernet putConstString put the string pointed to by s to the ENC transmit buffer ur unsigned int putString char s unsigned int ctr 0 while Spi Ethernet putByte s return ctr it will be much faster to use library Spi Ethernet putString rou tine 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 choose to go with the putString defini tion above the define line
212. IKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference JUMP STATEMENTS The jump statement when executed transfers control unconditionally There are four such statements in the mikroC PRO for AVR break continue goto return BREAK AND CONTINUE STATEMENTS Break Statement Sometimes it is necessary to stop the loop within its body Use the break statement within loops to pass control to the first statement following the innermost switch for while or do block Break is commonly used in the switch statements to stop its execution upon the first positive match For example 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 is true Specifically the continue statement within the loop will jump to the marked position as it is shown below while do if 1 gt 0 continue if val gt 0 continue continue jumps here continue jumps here while MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 215 CHAPTER 5 Langua
213. INB B5 Tone3 while PINB B5 if PINB B4 Melody2 while PINB B4 if PINB B3 Melody while PINB B3 mikroC PRO for AVR Configure PORTB as input Initialize sound pin Play starting sound 2kHz 1 second endless loop If PORTB 7 is pressed play Tonel Z4 Wait for button to be released If PORTB 6 is pressed play Tone2 Lf Wait for button to be released If PORTB 5 is pressed play Tone3 if Wait for button to be released If PORTB 4 is pressed play Melody2 77 Wait for button to be released If PORTB 3 is pressed play Melody 7 Wait for button to be released CHAPTER 6 mikroC PRO for AVR Libraries HW Connection J PIEZO SPEAKER VCC i 10K 10K 10K 10K PORTB B3 dis PORTB B4 gt gt L PORTB B5 OSCILLATOR m 6 gt L PORTB B7 e Example of Sound Library connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 425 CHAPTER 6 Libraries mikroC PRO for AVR SPI LIBRARY mikroC PRO for AVR provides a library for comfortable with SPI work in Master mode The AVR MCU can easily communicate with other devices via SPI A D converters D A converters MAX7219 LTC1290 etc
214. IONS FOR EMBEDDED WORLD 431 CHAPTER 6 Libraries External dependencies of SPI Ethernet Library The following variables must be defined in all projects using SPI Eth ernet Library Description xtern sfr sbit Ethernet RST e S extern sfr sbit SPI Ethernet CS Direc ti e S xtern sfr sbit PI Ethernet RST Dire 22 of the ENC28J60 nian reset pin The following routines must be defined in all project using SPI Ether net Library Description unsigned int SPI Ethernet UserTCP unsigned char remoteHost unsigned int remotePort unsigned int localPort unsigned int reqLength TCP request handler unsigned int SPI Ethernet UserUDP unsigned char remoteHost unsigned int remotePort unsigned int destPort unsigned int reqLength UDP request handler mikroC PRO for AVR PI Ethernet CS TB B4 PI Ethernet RST TB B5 Ethernet CS Direc t DDRB B4 Ethernet RST Dire ction at DDRB B5 Refer to the library exam ple at the bottom of this page for code implemen tation Refer to the library exam ple at the bottom of this page for code implemen tation 432 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Library Routines SPI Ethernet Init SPI Ethernet Enable SPI Ethernet Disable SPI Ethernet doPacket SPI Ethernet putByte SPI Ethernet putBytes SPI Ethernet put
215. IONS FOR EMBEDDED WORLD 441 CHAPTER 6 Libraries mikroC PRO for AVR SPI_Ethernet_getBytes void SPI Ethernet getBytes unsigned char ptr unsigned int addr unsigned char n Nothing This is MAC module routine It fetches equested number of bytes from ENC28360 RAM starting from given address If value of oxrrrr is passed as the address parameter the reading will start from current 28 760 read pointer ERDPT location Prototype Descnption Parameters ptr buffer for storing bytes read from 28 760 RAM addr ENC28J60 RAM start address Valid values 0 8192 n number of bytes to be read Ethernet module has to be initialized See SPI Ethernet Init char buffer 16 SPI Ethernet getBytes buffer 0 100 16 read 16 bytes starting from address 0x100 442 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI_Ethernet_UserTCP unsigned int SPI Ethernet UserTCP unsigned char remoteHost Prototype unsigned int remotePort unsigned int localPort unsigned int reqLength 0 there should not be a reply to the request Length of TCP HTTP reply data field otherwise This is TCP module routine It is internally called by the library The user access es to the TCP HTTP request by using some of the SPI Ethernet get routines The user puts data in the transmit buffer by using some of the SPI Ethernet put r
216. JUaWIWOD uonsenb 1 Aue MN ERNER SNOILAMIOS SUVMCYVH 3HVMLJOS EXIU01149130 DELIA E
217. KA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 83 CHAPTER 2 Environment mikroC PRO for AVR 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 the window containing the file that you want to save is the active window 2 Select File Save from the drop down menu or press Ctrl S or click the Save File Icon from the File Toolbar 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 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 Fil
218. KTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 31 CHAPTER 2 Environment mikroC PRO for AVR KEYBOARD SHORTCUTS Below is a complete list of keyboard shortcuts available in mikroC PRO for AVR IDE You can also view keyboard shortcuts in the Code Explorer window tab Keyboard F i 5 32 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Ctrl Shift O Ctrl Shift N Ctrl Shift F5 m mikroC PRO for AVR Ctrl X Ctrl Y Ctrl Z Ctrl Shift Z Advanced Editor Shortcuts Ctrl Space Ctrl Shift Space Ctrl D Ctrl E Ctrl L Ctrl G Ctrl J Ctrl Shift Ctrl Shift Ctrlt number Ctrl Shift number Ctrl Shift Ctrl Shift U AB Shift TAB Alt Select Ctrl Alt Select Ctril Alt L Ctri Alt U Ctrl Alt T CHAPTER 2 Environment MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 33 CHAPTER 2 Environment mikroC PRO for AVR eo rao kr eme _ 34 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment MIKROC PRO FOR AVR IDE IDE Overview The mikroC PRO for AVR is an user friendly and intuitive environment amp Pipon smira PRO for AX LORS 0 FlesiMiroeiektrankal bro PRO for AM LLL Od Message Test M Proc enn HF LOG 65 lt OILI 4010 A CA pvogam gt Ad Hes 15 The Code Editor features adjustable Synt
219. KTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 343 CHAPTER 6 Libraries mikroC PRO for AVR else file was not found signal it UART1 Write 0x55 Delay 1000 UART1 Write 0x55 a Tries to create a swap file whose size will be at least 100 sectors see Help for details void M Create Swap File unsigned int i for i 0 i 512 i Buffer i i size Mmc Fat Get Swap File 5000 mikroE txt 0x20 see help on this function for details if size LongToStr signed long size fat_txt I Write Str fat txt for i 0 1 lt 5000 i Write Sector size Buffer UART1 Write 7 Main Uncomment the function s to test the desired operation s void main we will use PORTC to signal test end DDRC OxFF PORTC 0 Spi Rd Pir SPTi Read use fati6 quick format instead of init routine if a format ting is needed if Mmc Fat Init reinitialize spi at higher speed SPI1 Init Advanced SPI MASTER SPI FCY DIV2 SPI CLK LO LEADING Test start Test routines Uncomment them one by one to test cer tain features 344 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries M Create New File M Create Multiple Files M Open File Rewrite M Open File Append M Open File Read M Delete File M Test File Exist M Crea
220. LIBRARY The mikroC PRO for AVR provides a library for communication with the Microchip s Port Expander 23517 via SPI interface Connections of the AVR compliant MCU and 23517 is given on the schematic at the bottom of this page Note Library uses the SPI module for communication The user must initialize SPI module before using the Port Expander Library Note Library does not use Port Expander interrupts External dependencies of Port Expander Library The following variables must be defined in all projects using Description Manchester Code Library extern sfr sbit Reset line sbit SPExpanderRST ExpanderRST at PORTB BO SP extern sfr sbit 2 sbit SPExpanderCS 5 5 Chip Select line at PORTB B1 extern sfr sbit Direction of the Sbit SPExpanderRST Direction Reset pin podras ipu het ee pin ction at DDRB B0 extern sfr sbit Direction of the Chip Sbir SPExpanderCS Direction Select pin EE me p tion at DDRB B1 Library Routines Expander Init Expander Read Byte Expander Write Byte Expander Read PortA Expander Read PortB Expander Read PortAB Expander Write PortA Expander Write PortB Expander Write PortAB Expander Set DirectionPortA Expander Set DirectionPortB Expander Set DirectionPortAB Expander Set PullUpsPortA Expander Set PullUpsPortB Expander Set PullUpsPortAB MIKROELEKTRONIKA SOFTWARE AND HARDWARE SO
221. LUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries for k 0 k lt 512 k UART1_Write dData k send 512 bytes from MMC card via usart printhex dData k UART1 Write if k 1 16 0 UART1 Write printhex k for px k 15 px lt k pxtt if dDatal px gt 33 dDatal px lt 126 UART1 Write dData px else UART1 Write UART1 Write 13 UART1 Write 13 UART1 Write 10 else UART1 Write Text Read error UART1 Write 13 UART1 Write 10 if serial buffer 0 W Command Write if serial buffer 1 w Generating 32 bit address of the sector out of four received bytes sector address long first_byte lt lt 24 long sec ond byte lt lt 16 long third byte lt lt 8 long fourth byte for k 0 k 512 k dData received character fill RAM baffer i Mmc Write Sector sector address dData write buffer tou MMC if i 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 339 CHAPTER 6 Libraries UAR UAR UAR else UAR UART UAR Write Text Write error r1 Write 13 r1 Write 10 Tl Write Text Write Ok Write 13 r1 Write 10 if serial buffer 0 C received character serial buffer 1 mikroC PRO for AVR 340 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR
222. LUTIONS FOR EMBEDDED WORLD 353 CHAPTER 6 Libraries mikroC PRO for AVR Expander Init Prototype Expander Init char ModuleAddress Initializes Port Expander using SPI communication Port Expande r module settings hardware addressing enabled automatic address pointer incrementing disabled byte mode Description BANK 0 register adressing slew rate enabled Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page es SPI module needs to be initialized See SPI Init and SPI Init Advanced routines Port Exp sbit SPExp sbit SPExp sbit SPExp sbit SPExp End Port Pointer char SPI Port SPI Rd Ptr Read functi SPIL Init used with P Expander In 354 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD MIKROELEKTRONIKA Global variables SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin Requires i ee SPExpanderRST Direction Direction of the Reset pin must be defined before using this function ander module connections anderRST at PORTB BO anderCS at 1 anderRST Direction at DDRB BO anderCS Direction at DDRB B1 Expander module connections to appropriate SPI Read function Rd Ptr char Expander Library uses SPI1 module amp SPI1 Read Pass pointer to S
223. Led 3 0 0 acce a tet edad Meee e 310 Available Lcd Commands 310 Library Example esate emer ee 311 Manchester Code Library 313 External dependencies of Manchester Code Library 314 Library Routines EEEE EEEE ek ee a RA 314 Man Receive Init 315 316 Man Send Geek ae ee dn 316 Man Send 317 Man Synchro 5d debba debba etie bebe ires edie 317 Man Break 318 Library 319 Connection Example 321 Multi Media Card Library 323 Secure Digital Card 323 External dependecies of MMC Library 323 Library RoutineS 324 Init eee Rs 325 Mmc Read Sector 325 Mmc Write Sector 326 Mmc Read 326 Mme Read win caked da eee he ee aE SERA 326
224. MCU for work with the PS 2 keyboard Global variables PS2 Data Data signal line PS2 In Clock Clock signal line in Requires PS2 Out Clock Clock signal line out PS2 Data Direction Direction of the Data pin PS2 Clock Direction Direction of the Clock pin must be defined before using this function sbit PS2 Data at PINC B0 sbit PS2 In Clock at PINC B1 sbit PS2 Out Clock at PORTC B1 sbit PS2 Data Direction at DDRC B0 sbit PS2 Clock Direction at DDRC B1 Ps2 Config Init PS 2 Keyboard MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 367 CHAPTER 6 Libraries mikroC PRO for AVR Ps2_Key_Read unsigned short Ps2 Key short value unsigned short Prototype special unsigned short pressed 1 if reading of a key from the keyboard was successful 0 if no key was pressed The function retrieves information on key pressed Parameters value holds the value of the key pressed For characters numerals Description punctuation marks and space value will store the appropriate ASCII code Routine recognizes the function of Shift and Caps Lock and behaves appropriately For special function keys see Special Function Keys Table special is a flag for special function keys F1 Enter Esc etc If key pressed is one of these special will be set to 1 otherwise O pressed is set to 1 if the key is pressed and O if it is released PS 2 keyboard needs to be
225. Main Perform main initialization value 2048 When program starts DAC gives the output in the mid range while 1 Endless loop if PINA BO amp amp value lt 4095 If PAO button is pressed value 2 increment value else if PINA B1 amp amp value gt 0 If 1 button is pressed value decrement value DAC Output value Send value to DAC chip Delay ms 1 Slow down key repeat pace 414 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SOFTWARE UART LIBRARY The mikroC PRO for AVR provides routines for implementing Software UART com munication These routines are hardware independent and can be used with any MCU The Software UART Library provides easy communication with other devices via the RS232 protocol Note The Software UART library implements time based activities so interrupts need to be disabled when using it External dependencies of Software UART Library The following variables must be defined in all ee Description projects using Software UART Library extern sfr sbit Receive line sbit Soft UART Rx Pin Soft UART Rx Pin at PIND BO extern sfr sbit sbit Soft UART Tx Pin Soft UART Tx Pin Transmit line at PORTD B1 Direction of the Receive Rx Pin Dire pin DDRD B0 sbit Soft UART Tx Pin Dire ction at DDRD B1 Direction of the Transmit
226. Messages are multi byte so this routine must be called for each byte received Parameters data buffer 6 byte buffer for storing received data in the following Description 21 message content number of message bytes received 1 3 is set to 255 when message is received is set to 255 if error has occurred The function automatically adjusts 4 and 5 upon every received message These flags need to be cleared by software R ir MCU must be initialized as a Slave for RS 485 communication See equire Rs4asSlave Init char msof 8 RS485Slave Read msg MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 395 CHAPTER 6 Libraries mikroC PRO for AVR RS485Slave_Send Prototype void RS485Slave Send char data buffer char datalen Description Sends message to Master Message format can be found at the bottom of this page Parameters data buffer data to be sent datalen number of bytes for transmition Valid values 0 3 MCU must be initialized as a Slave for RS 485 communication See RS485Slave Init It is the user s responsibility to ensure by protocol that only one device sends data via 485 bus at a time char msof 8 send 2 bytes of data to the Master RS485Slave Send msg 2 Library Example Library Example This is a simple demonstration of RS485 Library routines usage Master sends message to Slave with address 160 an
227. NIKA ASSOCIATES OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL INCIDENTAL INDIRECT OR CONSEQUENTIAL DAMAGES WHATSOEVER INCLUDING WITHOUT LIMITATION DAMAGES FOR LOSS OF BUSINESS PROFITS AND BUSINESS INFORMATION BUSINESS INTERRUPTION ORANY OTHER PECUNIARY LOSS ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE PRODUCT OR THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES EVEN IF MIKROELEKTRONIKA ASSOCIATES HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES IN ANY CASE MIKROELEKTRONIKA ASSOCIATES ENTIRE LIABILITY UNDER ANY PROVISION OF THIS LICENSE AGREEMENT SHALL BE LIMITED TO THE AMOUNT ACTUALLY PAID BY YOU FOR SOFTWARE PRODUCT PROVIDED HOWEVER IF YOU HAVE ENTERED INTO A MIKROELEKTRONIKAASSOCIATES SUPPORT SERVICES AGREEMENT MIKROELEKTRONIKA ASSOCIATES ENTIRE LIABILITY REGARDING SUPPORT SERVICES SHALL BE GOVERNED BY THE TERMS OF THAT AGREEMENT MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 9 CHAPTER 1 Introduction mikroC PRO for AVR HIGH RISK ACTIVITIES Software is not fault tolerant and is not designed manufactured or intended for use or resale as on line control equipment in hazardous environments requiring fail safe performance such as in the operation of nuclear facilities aircraft navigation or communication systems air traffic control direct life support machines or weapons systems in which the failure of Software could lead directly to death personal injury or severe physical or e
228. O for AVR Environment s already used lLevel can be used only with interrupt service routines expected but s found Expected 96s Identifier redefined expected but s found J expected but s found case out of switch expected but ss found default label out of switch switch expression must evaluate to integral type while expected but 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 Level can be used only with interrupt service routines Level value must be integral constant Level out of range 0 4 expected 5 found J expected but s found break outside of loop or switch Empty char Nonexistent field 55 Illegal char representation 5s Initializer syntax error multidimensional array missing subscript Too many initializers of subaggregate At least one Search Path must be specified Not enough RAM for call stack Demo Limit Parameter 2s must not be of bit or sbit type Function must not have return value of bit or sbit type MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 89 CHAPTER 2 Environment mikroC PRO for AVR Compiler Warning Messages Bad or missing fosc param
229. OLUTIONS FOR EMBEDDED WORLD 27 CHAPTER 2 Environment mikroC PRO for AVR RUN MENU OPTIONS Start Debugger Stop Debugger Pause Debugger Step Into Step Over Step Out Jump To Interrupt F2 Toggle Breakpoint F5 Breakpoints Shift4F4 Clear Breakpoints Shift4Ctrl4F5 d Watch Window Shift F5 View Stopwatch Disassembly mode 28 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment Run Description 9 Start Software Simulator Stop Debugger Ctrl F2 Stop debugger Eh Pause Debugger F6 Pause Debugger O StepInto F7 Step Into 44 Step Over F8 Step Over O Step Ctrl F8 Step Out Jump Interrupt Jump to interrupt in current project Toggle Breakpoint FS Toggle Breakpoint Show Hide Breakpoints Shift F4 Breakpoints Be Clear Breakpoints Shift Ctrl F5 Clear Breakpoints 6S Watch Window Shift FS Show Hide Watch Window 5 View Stopwatch Show Hide Stopwatch Window Disassembly mode Ctrl D Toggle between C source and disassembly Related topics Keyboard shortcuts Debug Toolbar MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 29 CHAPTER 2 Environment 30 TOOLS MENU OPTIONS mE Programmer Fil USART Terminal Ctrl T EEPROM Editor Ascii Chart Seven Segment Convertor Export Code
230. PI on of used SPI module Initialize SPI module ortExpander at Initialize Port Expander SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Expander_Read_Byte Prototype char Expander Read Byte char ModuleAddress char RegAddress The function reads byte from Port Expander Parameters Description ModuleAddress Port Expander hardware address see schematic at the bottom of this page RegAddress Port Expander s internal register address Port Expander must be initialized See Expander_Init Read a byte from Port Expander s register char read data read data Expander Read Byte 0 1 Expander Write Byte void Expander Write Byte char ModuleAddress char RegAddress char Prototype Routine writes a byte to Port Expander Parameters Description ModuleAddress Port Expander hardware address see schematic at the bottom of this page RegAddress Port Expander s internal register address Data data to be written Requires Port Expander must be initialized See Expander_Init Example Write a byte to the Port Expander s register Expander Write Byte 0 1 FF MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 355 CHAPTER 6 Libraries 356 mikroC PRO for AVR Expander_Read_PortA Prototype char Expander Read PortA char ModuleAddress Description The function reads
231. PROM Tool i E E PROM Editor F Use Eeprom in project Device EEPROM Size EEPROM Fill EEPROM File Custom 7 _ 51a Bytes Yalue Ox FF Load Save EEPROM Data Addr 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF JyyyyYYVYYVYVYYY 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 EEPROM Edit Input Format 44 Edit Value EEPROM Address Hex Start Address Ox FFFF Size Float AutoInc Byte Word DWord String
232. Pee eee 243 CANSPI Constants 244 CANSPI_OP_MODE 244 CANSPI_CONFIG_ FLAGS 244 TX MSG FLAGS 0 20000 cece eee 245 RX MSG FLAGS 246 aiou aad ub dr e une os y Su bt 246 CANSPI FIETER eos Rn RERO RR Rm 247 Library 22 pe bs 247 HW Connection 250 Compact Flash 251 External dependencies of Compact Flash Library 252 Library Routines 253 i hae 254 Cf Detect ER ne we RRS ee ERU OR 255 Cf Enable 4 obese hha Co be VER HAV ER dd 255 Cf Disable oc egre ek RU a dte n 255 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD XV Table of Contents mikroC PRO for AVR Ci Read nlt ies os ceu RAE sc x REESE DeC Re des 256 Cf Read Byte 256 CT Wite Mit coute oa ee hard E 257 Cf Write Byte 257 Cf Read Sector 258 C
233. R HW Connection T eee 100 1K 1K N e 3 a s S3 1 Wo 7 71 al MIS03 3 Co e 3053 m H ETH CS A2 RD E 51R Bn 1 518 1 j amp AB 452 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI GRAPHIC LCD LIBRARY The mikroC PRO for AVR 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 Prior to calling any of this library routines Spi_Rd_Ptr needs to be initialized with the appropriate SPI Read routine E
234. R 6 Libraries 570 Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Left justify the output in the specified field width Prefix the output value with or sign if the output is a signed type Prefix the output value with a blank if it is a signed positive value Otherwise no blank is prefixed Prefixes a non zero output value with 0 0x or ox when used with o x and x field types respectively When used with e E f g and c 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 is a non negative number that specifies the minimum number of printed characters If a number of characters in the output value is less than width then blanks are added on the left or right when the flag is specified to pad to the minimum width If width is prefixed with 0 then zeros are padded instead of blanks The width field never truncates a field If a length of the out put value exceeds the specified width all characters are output The precision field is a non negative number that specifies a number of char acters to print number of significant digits or number of decimal places The precision field can cause truncation or rounding of the output value in the case of a floating point number as specified in the following table Meaning of the precision field The preci
235. R 6 mikroC PRO for AVR Libraries Library Example The example is a simple demonstration of how to use the Sound Library for playing tones on a piezo speaker Sound connections sbit Sound Play Pin at PORTC B3 sbit Sound Play Pin direction at DDRC B3 End Sound connections void Tonel Sound Play 500 200 Frequency 500Hz Duration 200ms void Tone2 Sound Play 555 200 Frequency 555Hz Duration 200ms void Tone3 Sound Play 625 200 Frequency 625Hz Duration 200ms void Melody Plays the melody Yellow house Tonel Tone2 Tone3 Tone3 Tonel Tone2 Tone3 Tone3 Tonel Tone2 Tone3 Tonel Tone2 Tone3 Tone3 Tonel Tone2 Tone3 Tone3 Tone3 Tone2 Tone2 1 void ToneA Tones used in Melody2 function Sound Play 1250 20 void ToneC Sound Play 1450 20 void ToneE Sound Play 1650 80 void Melody2 Plays Melody2 unsigned short i for i 9 i 0 i ToneA ToneC ToneE MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 423 CHAPTER 6 Libraries 424 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD void main DDRB 0x00 Sound_Init Sound Play 500 while 1 if PINB B7 1 while 7 if PINB B6 Tone2 while PINB B6 if P
236. RO for AVR Libraries Man_Send Prototype Man Send unsigned char tr data Sends one byte Parameters Description tr data data to be sent Note Baud rate used is 500 bps To use this function the user must prepare the MCU for sending See Requires Man Send Init unsigned char msg Man _Send msg Man_Synchro Prototype unsigned char Man _ Synchro 255 if synchronization was not successful Half of the manchester bit length given in multiples of 10us upon successful synchronization Measures half of the manchester bit length with 10us resolution To use this function you must first prepare the MCU for receiving See Requires Man Receive Init unsigned int man half bit len man half bit len Man Synchro MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 317 CHAPTER 6 Libraries mikroC PRO for AVR Man_Break Man Receive is blocking routine and it can block the program flow Call this rou tine from interrupt to unblock the program execution This mechanism is similar Description Note Interrupts should be disabled before using Manchester routines again see note at the top of this page char datal error counter 0 void TimerOOverflow ISR org 0x12 if counter gt 20 Man Break counter 0 reset counter else counter increment counter void main TOIEO bit TimerO overflow inter
237. ROM A ASCII Chart E 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 25 CHAPTER 2 Environment 26 mikroC PRO for AVR PROJECT MENU OPTIONS Build Ctrl F9 Build All Projects Shift F9 Build Program Ctri F11 Edit Search Paths Clean Project Folder Add File To Project Remove File From Project 2 New Project Shift Ctrl N Open Project Shift Ctrl O F Open Project Group Close Project Group Save Project As Recent Projects Close Project MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment Project Description Build active project Build all projects Build and program active project Edit search paths Clean Project Folder Add file to project Remove file from project Open New Project Wizard Open existing project Save current project Close project group Save active project file with the different name Open recently used project Close active project Related topics Keyboard shortcuts Project Toolbar Creating New Project Project Manager Project Settings MIKROELEKTRONIKA SOFTWARE AND HARDWARE S
238. RP Eh s pass 140 Pound Sign Preprocessor Directive 141 Concepts 225 55 55 OR deena eee IRURE ROS XU OUR NR CAUSA ITO RR S 142 Objects koe uem ieee e Od Uer ROTER RR ET ERG Edu 142 Objects and Declarations 142 iia ss dae bole ENT RIS 143 Rvalues Oc bp ER ERA e Retos Ve de backed 143 Scope and Visibility 144 CONG c usce uei Ru PM EE 144 MVISIDINGY 2 eae 144 Name Spaces 146 Duration x EE ORAE e ACCRUE UC RASA 147 Static Duration 147 Local Duration i 4400 4 re ect DER m ER dem Rn de ded 147 TYPOS 149 X MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Table of Contents Type Categories 422222294 po Ree d yoke 149 Fundamental Types 150 Arithmetc Typ S uet EE Sor UR eee eee d 150 Integral TVpes 22 uei 150 Floating point Types 151 Enumerations 2 572 ha Gea ee a Oe OM 152 Enumeration Declaration 152 Anonymous Enum Type
239. RT connections sbit Soft UART Rx Pin at PIND BO sbit Soft Tx Pin at PORTD B1 sbit Soft UART Rx Pin Direction at DDRD B0 sbit Soft UART Tx Pin Direction at DDRD B1 End Soft UART connections char i error byte read Auxiliary variables void main DDRB OxFF Set PORTB as output error signalization PORTB 0 No error error Soft UART Init 9600 0 Initialize Soft UART at 9600 bps if error gt 0 PORTB error Signalize Init error while 1 Stop program Delay ms 100 for i z i gt A i Send bytes from z downto A Soft UART Write i Delay ms 100 while 1 Endless loop byte read Soft UART Read amp error Read byte then test error flag if error If error was detected PORTB error FE signal it on PORTB else Soft UART Write byte read If error was not detect ed return byte read 420 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SOUND LIBRARY The mikroC PRO for AVR provides a Sound Library to supply users with routines necessary for sound signalization in their applications Sound generation needs additional hardware such as piezo speaker example of piezo speaker interface is given on the schematic at the bottom of this page External dependencies of Sound Library The following variables must be defined in all TE 5 Description p
240. RoutineS 403 Soft 2C Init a Ra RRE eels an ae eee S 403 Soft I2C Starts diss walle wade tae E GR RA CR 404 SOM 20 Read sexes xe E ee xat eR dodo nan eS 404 Soft 126 Write 2 222 22 7 2 4 4 Aeon 405 Soft C Stop sss rra uu REOR RARO CR RA a 405 Sot 126 Break er ee edes 406 Library 407 Software SPI Library 410 External dependencies of Software SPI Library 410 Library Routines 411 SOM SPAN bag ev eR Eu enr EX epe Re E ES 411 Soft Read uae ce x une e px Rie XO Rn we 412 Soft WIO iiir beer Madd ib bd 412 Library Example Rm pb DA Dun Res 413 Software UART Library 415 External dependencies of Software UART Library 415 Library Routines 415 SOft UART Init 1 532 32 2L Tace ew Bea a AE Hs 416 Soft ART Read 2255 wage Rn Sea a 417 Soft UART Write 418 UART 419 Library Example sse Rl 420 Sound library
241. Rx space However since compiler uses Rx space for storing temporary variables it might happen that user variables will be stored in the internal data SRAM when writing complex programs puts y in Rx space sfr char rx y Description This memory specifier allows user to access the I O Memory space put PORTB in io memory space sfr io unsigned short PORTB absolute 0x38 sfr This memory specifier in combination with rx io data allows user to Description access special function registers It also instructs compiler to maintain same identifier in C and assembly Sfr io unsigned short PORTB absolute 0x38 put PORTB in I O memory space sfr rx char y puts y in Rx space sfr data unsigned short PORTG absolute 0x65 and sfr unsigned short PORTG absolute 0x65 are equivalent and put PORTG in Extended I O Space Note If none of the memory specifiers are used when declaring a variable data specifier will be set as default by the compiler Related topics AVR Memory Organization Accessing individual bits SFRs Constants Func tions 118 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER mikroC PRO for AVR Language Reference The mikroC PRO for AVR Language Reference describes the syntax semantics and implementation of the mikroC PRO for AVR language The aim of this reference guide is to provide a more understandable description of the mikroC PRO for AVR language to the
242. SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Code for the second 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 Data 8 can rx tx data buffer char Msg Rcvd reception flag long Tx ID Rx ID can rx and tx ID CANSPI module connections sbit CanSpi CS PORTB B0 sbit CanSpi CS Direction at DDRB B0 sbit CanSpi Rst at PORTB B2 sbit CanSpi Rst Direction at DDRB B2 End CANSPI module connections void main PORTC 0 clear PORTC DDRO 255 set PORTC as output Can Init Flags 0 Can Send Flags 0 clear flags Rev Flags 0 Can Send Flags 5 TX PRIORITY 0 amp form value to be used CANSPI TX XTD FRAME amp with CANSPIWrite CANSPI TX NO RTR FRAME Can Init Flags CANSPI CONFIG SAMPLE THRICE amp orm value to be used CANSPI CONFIG PHSEG2 PRG ON amp with CANSPIInit CANSPI CONFIG XTD MSG amp CANSPI CONFIG DBL BUFFER ON amp CANSPI CONFIG VALID XTD MSG amp CANSPI CONFIG LINE FILTER OFF Inzt Spi Rd Ptr 5 1 Read pass pointer to SPI Read function of used SPI module Inzt initialize SPI1 module CANSPIInitialize 1 3 3 3 1 Can Init Flags initialize exter nal CANSPI module CANSPISetOperationMode C
243. Scl Direction at DDRC B0 sbit Soft I2C Sda Direction at DDRC B1 End Software I2C connections LCD module connections sbit LCD RS at PORTD B2 sbit LCD EN at PORTD B3 sbit LCD D4 at PORTD B4 sbit LCD D5 at PORTD B5 sbit LCD D6 at PORTD B6 sbit LCD D7 at PORTD B7 sbit LC sbit LC sbit LC Direction at DDRD B2 EN Direction at DDRD B3 D4 Direction at DDRD B4 sbit LCD D5 Direction at DDRD B5 sbit LCD D6 Direction at DDRD B6 sbit LCD D7 Direction at DDRD B7 End LCD module connections KJ CS KJ TU Ru E TA CJ W a Reads time and date information from RTC PCF8583 void Read Time Soft I2C Start Issue start signal Soft I2C Write 0xA0 Address PCF8583 see PCF8583 datasheet Soft I2C Write 2 Start from address 2 Soft I2C Start Issue repeated start signal Soft I2C Write 0xA1 Address PCF8583 for reading R W 1 seconds Soft I2C Read 1 Read seconds byte minutes Soft I2C Read 1 Read minutes byte hours Soft I2C Read 1 Read hours byte day Soft I2C Read 1 Read year day byte month Soft I2C Read 0 Read weekday month byte Soft 120 Stop 7 Issue stop signal MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 407 CHAPTER 6 Libraries mikroC PRO for AVR 408 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
244. Select pin Requires SPExpanderRST Direction Direction of the Reset pin must be defined before using this function The SPI module needs to be initialized See SPI1 Init and SPI1 Init Advanced routines Port Expander module connections sbit SPExpanderRST at PORTB BO sbit SPExpanderCS at PORTB B1 sbit SPExpanderRST Direction at DDRB BO sbit SPExpanderCS Direction at DDRB B1 End Port Expander module connections If Port Expander Library uses SPI1 module SPIL Init Initialize module used with PortExpander SPI Rd Ptr SPI1 Read Pass pointer to SPI Read function of used SPI module SPI Lcd8 Config 0 intialize Led in 8bit mode via SPI MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 477 CHAPTER 6 Libraries mikroC PRO for AVR SPI Lcd8 Out void SPI Lcd8 Out unsigned short row unsigned short column char Prototype texti Prints text on Lcd starting from specified position Both string variables and liter als can be passed as a text T Parameters Description row Starting position row number column Starting position column number text text to be written Requires Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routines Write text Hello on Lcd starting from row 1 column 3 SPI Leds Out l 3 Hello SPI Lcd8 Out Cp Prints text on Lcd at current cursor position Both string variables and l
245. SoftSpi SDO at SoftSpi SDO Data Out line PORTB B5 extern sfr sbit Clock line sbit SoftSpi CLK at SoftSpi CLK PORTB B7 Description extern sfr sbit Direction of the Chip sbit Chip Select at Chip Select select pin PINB B6 extern sfr sbit Direction of the Data Pit Chip Select Di tione lpi Chip Select Direction ip Select Direction pin at DDRB B0 sbit extern sfr sbit Direction of the Data Out SoftSpi SDO Di iene SoftSpi SDO Direction seen pum weno at DDRB B5 extern sfr sbit SoftSpi CLK Direction Direction DRB B7 410 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Library Routines Soft SPI Init Soft SPI Read Soft SPI Write Soft SPI Init CHAPTER 6 Libraries Prototype Configures and initializes the software SPI module Global variables Chip Select Chip_Select line SoftSpi SDI Data SoftSpi SDo Data SoftSpi CLK Data Chip Select Direction Direction of the Chip Select Direction pin SoftSpi S SoftSpi S SoftSpi CI in line out line clock line DI Direction Direction of the Data in pin DO Direction Direction of the Data out pin LK Direction Direction of the Data clock pin must be defined before using this function Software SPI module connections sbit sbit sbit sbit sbit sbit sbit Chip Select at PORI SoftSpi C SoftSpi SDI SoftSpi SDO at PORI Ch
246. String SPI Ethernet putConstString SPI Ethernet putConstBytes SPI Ethernet getByte SPI Ethernet getBytes SPI Ethernet UserTCP SPI Ethernet UserUDP The following routines are for the internal use by compiler only SPI Ethernet arpResolve SPI Ethernet checksum SPI Ethernet clearBitReg SPI Ethernet confNetwork SPI Ethernet delay SPI Ethernet DHCPmsg SPI Ethernet DHCPReceive SPI Ethernet dnsResolve SPI Ethernet doARP SPI Ethernet doDHCP SPI Ethernet doDHCPLeaseTime SPI Ethernet doDNS SPI Ethernet doTCP SPI Ethernet doUDP SPI Ethernet getDnslpAddress SPI Ethernet getGwlpAddress SPI Ethernet getlpAddress SPI Ethernet getlpMask SPI Ethernet Init2 SPI Ethernet initDHCP SPI Ethernet IPswap SPI Ethernet MACswap SPI Ethernet memcmp SPI Ethernet memcpy SPI Ethernet pktLen SPI Ethernet RAMcopy SPI Ethernet readMem SPI Ethernet readPacket SPI Ethernet readPHY SPI Ethernet readReg MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 433 CHAPTER 6 Libraries mikroC PRO for AVR SPI Ethernet renewDHCP SPI Ethernet sendUDP SPI Ethernet sendUDP2 SPI Ethernet setBitReg SPI Ethernet setRxReadAddress SPI Ethernet TXpacket SPI Ethernet writeAddr SPI Ethernet writeMem SPI Ethernet writeMemory SPI Ethernet writeMemory2 SPI Ethernet writePHY SPI Ethernet writeReg SPI Ethernet Init Desc
247. T6963C SetPtr Prototype void T6963C SetPtr unsigned int p unsigned char c Sets the memory pointer p for command c Parameters Description 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 T6963C SetPtr T6963C grHomeAddr start T6963C ADDRESS POINTER SET T6963C WaitReady Pools the status byte and loops until Toshiba GLCD module is ready Toshiba GLCD module needs to be initialized See the T6963C Init routine RR NN MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 511 CHAPTER 6 Libraries mikroC PRO for AVR T6963C_Fill void T6963C Fill unsigned char v unsigned int start unsigned int len Fills controller memory block with given byte Prototype Parameters Description v byte to be written start Starting address of the memory block len length of the memory block in bytes Toshiba GLCD module needs to be initialized See the T6963C Init routine 00000000 T6963C_Dot Prototype 6963 Dot int x int y unsigned char color Draws a dot in the current graphic panel of GLCD at coordinates x y Parameters Description x dot position on x axis y dot position on y axis color color parameter Valid values T6963C BLACK and T6963C WHITE Toshiba
248. TER 6 mikroC PRO for AVR Libraries filename 7 C Cf Fat Assign amp filename 0 Cf Fat Rewrite for loop 1 loop lt 55 1 file contents 0 loop 10 64 file contents 1 loop 10 64 Cf Fat Write file contents 38 write data to the assigned file Opens an existing file and appends data to it and alters the date time stamp void M Open File Append filename 7 B Cf Fat Assign amp filename 0 Cf Fat Set File Date 2005 6 21 10 35 0 Cf Fat Append Prepare file for append Cf Fat Write for mikroElektronika 2005n 27 Write data to assigned file 2 e Opens an existing file reads data from it and puts it to USART void M Open File Read filename 7 B Cf Fat Assign amp filename 0 Cf Fat Reset amp size To read file procedure returns size of file for i 1 i lt size i Cf Fat Read amp caracter UART1 Write caracter Write data to USART gd ee 4 Deletes a file If file doesn t exist it will first be created then deleted void M Delete File filename 7 F Cf Fat Assign filename 0 Cf Fat Delete MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 271 CHAPTER 6 Libraries mikroC PRO for AVR Tests whether file exists if so sends its cre ation date ZZ and file size via USART voi
249. TIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries PWM1 Set Duty Prototype PWM1 Set Duty unsigned short duty Changes PWM duty ratio Parameter duty takes values from 0 to 255 where 0 Description is 0 127 is 50 and 255 is 100 duty ratio Other specific values for duty ratio can be calculated as Percent 255 100 PWM module must to be initialised PWM1_Init before using PWM Set Duty Requires function For example lets set duty ratio to 75 bom PWM1 Set Duty 192 PWMA Start MCU must have CMO module to use this library PWM1 Init must be called before using this routine PWM1 Stop Stops the PWM MCU must CMO module to use this library PWM1 Init and PWM1 Start must be called before using this routine using this routine otherwise it will have no effect as the PWM module is not running MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 379 CHAPTER 6 Libraries mikroC PRO for AVR Library Example The example changes PWM duty ratio on pin PB3 continually If LED is connected to PB3 you can observe the gradual change of emitted light char current duty char current dutyl void main DDBO 0 Set PORTB pin 0 as input DDB1 0 Set PORTB pin 1 as input DDCO 0 Set PORTC pin 0 as input DDC1 0 Set PORTC pin 1 as input current duty 127 initial value for current duty current dutyl 127 initial value for c
250. TIONS FOR EMBEDDED WORLD 261 CHAPTER 6 Libraries mikroC PRO for AVR Cf_Fat_Rewrite adr currently assigned file for writing If the file is not empty its content will be CF card and CF library must be initialized for file operations See Cf Fat Init The file must be previously assigned See Cf Fat Assign open file for writing Cf Fat Rewrite Cf Fat Append Opens currently assigned file for appending Upon this function execution file Description pointers will be positioned after the last byte in the file so any subsequent file writing operation will start from there CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign open file for appending Cf Fat Append Cf Fat Delete Deletes currently assigned file from CF card CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign delete current file Ct Fat Delete 7 262 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Cf_Fat_Write Prototype void Cf Fat Write char fdata unsigned data len Writes requested number of bytes to currently assigned file opened for writing er Parameters Description fdata data to be written data len number of bytes to be written CF card and CF library must be initialized for file
251. The statement executes repeatedly until the value of expression is false The test takes place before statement is executed Thus if expression evaluates to false on the first pass the loop does not execute Note that parentheses around expres sion are mandatory Here is an example of calculating scalar product of two vectors using the while statement int s 0 i 0 while i lt S afi bl il Thy Note that body of the loop can be a null statement For example while tatt prt 212 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference DO STATEMENT The do statement executes until the condition becomes false The syntax of the do statement is do statement while expression The statement is executed repeatedly as long as the value of expression remains non zero The expression is evaluated after each iteration so the loop will execute statement at least once Parentheses around expression are mandatory Note that do is the only control structure in C which explicitly ends with semicolon 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 statement do S t ali while lt MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 213 CHAPTER
252. To HTML LCD Custom Character GLCD Bitmap Editor UDP Terminal Options mikroC PRO for AVR Tools Description USART Terminal Run USART Terminal EEPROM Editor Run EEPROM Editor a mE Programmer 11 Run mikroElektronika Programmer i C Ascii Chart Run ASCII Chart Ej Seven Segment Convertor Run 7 Segment Display Decoder Generate HTML code suitable for publishing source code on the web iu Export Code To HTML Generate your own custom LCD characters LCD Custom Character GLCD Bitmap Editor Generate bitmap pictures for GLCD UDP Terminal UDP communication terminal af Options Fiz Open Options window Related topics Keyboard shortcuts Tools Toolbar MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment HELP MENU OPTIONS Help F1 Check For Updates mikroElektronika Support Forums mikroElektronika Web Page How To Register About Description Help File Quick Help Check For Updates Check if new compiler version is available Open mikroElektronika Support Forums in a default browser Open mikroElektronika Web Page in a default browser mikroElektronika Support Forums mikroElektronika Web Page How To Register Information on how to register Open About window Related topics Keyboard shortcuts MIKROELE
253. UTIONS FOR EMBEDDED WORLD 311 CHAPTER 6 Libraries mikroC PRO for AVR while 1 Endless loop for i 0 i lt 7 i Move text to the left 7 times Lcd Cmd LCD SHIFT LEFT Move Delay for i 0 i 7 i Move text to the right 7 times Lcd Cmd LCD SHIFT RIGHT Move Delay VCC OSCILLATOR 9LVOJNWLV LCD 2X16 Lcd HW connection 312 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries MANCHESTER CODE LIBRARY The mikroC PRO for AVR 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 O 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 sti sq or B7 86 85 84 85 82 67 60 Bi phase coding ru 1 9 2ms Example of transmission 11000100011 Notes The Manchester receive routines are blocking calls Receive Init and Man Synchro This means that MCU will wait until the task has been performed e g byte is received synchronization achieved etc Note Manchester code library implem
254. Usage 53 RAM 53 Rx Memory Space 53 Data Memory Space 54 Special Function Registers 54 General Purpose Registers 55 ROM Memory eredes ne eee a EE HERE Rb 55 ROM Memory 55 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD V Table of Contents mikroC PRO for AVR ROM Memory Allocation 56 Procedures 5 56 Procedures Size Window 57 Procedures Locations Window 57 HTML Window 58 Macro Editor 5222 dise ese 59 Integrated Tools 22 5 vag d se cage Cea ved ck e Pepa 60 USART a area nae etas ex ue eeu 60 ASGII Chart 25 Ree ee 61 EEPROM 62 7 Segment Display Decoder 63 UDP Terminals 2 uel eee se eae eed ERU 64 Graphic LCD Bitmap Editor 65 LCD Cus
255. V Line 2 54 counter 1 SPI Glcd H Line 2 120 counter 1 Delay2s SPI Glcd Fill 0x00 7 Clear Glod SPI Glcd Set Font Character8x7 8 8 32 Choose font see Lib GlcdFonts c in Uses folder SPI Gled Write Text mikroE 5 7 2 Write string r counter 1 counter lt 10 counter Draw circles SPI Circle 63 32 3 counter 1 Delay2s KTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR 1 12 20 Delay2s T0763 SPI Glcd Fill 0xFF 2 SPI Glcd Set Font Character8x7 someText 8x7 Font SPI Gled Write Text someText SPI Glcd Write Text someText Delay2s SPI Glcd Set Font System3x5 someText 5 5 3 3X5 CAPITALS ONLY SPI Glcd Write Text someText SPI Gled Write Text someText Delay2s SPI Gled Set Font font5x7 someText 5 7 Pont 5 SPI Glcd Write Text someText SPI Glcd Write Text someText Delay2s SPI Glcd Set Font FontSystem5x7 v2 someText Font w2 SPI Gled Write Text someText SPI Glcd Write Text someText Delay2s MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 5 5 5 5 8 5 CHAPTER 6 Libraries Draw box Fill Glcd 7 82 Change font 0 2 Write string 1 2 Write string Change font 2 2 Write string 3
256. VR Assignment Rules For both simple and compound assignment the operands expressioni and expression2 must obey one of the following rules 1 2 expressioni is of qualified or unqualified arithmetic type and expression2 is of arithmetic type expressionl 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 is 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 is a null pointer constant MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference 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 Ivalue that designates a bit field object Sizeof Appli
257. VR Libraries 230 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries ADC LIBRARY ADC Analog to Digital Converter module is available with a number of AVR micros Library func tion ADC_Read is included to provide you comfortable work with the module in single ended mode ADC_Read Prototype unsigned ADC Read char channel Returns 10 bit or 12 bit MCU dependent unsigned value from the specified cnanne1 Initializes AVR s internal ADC module to work with XTAL frequency prescaled by 128 Clock determines the time period necessary for performing A D conver 22 sion Description Parameter channel represents the channel from which the analog value is to be acquired Refer to the appropriate datasheet for channel to pin mapping Requires Nothing p tmp pun ADC Read 2 Read analog value from channel 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 231 CHAPTER 6 Libraries mikroC PRO for AVR Library Example This example code reads analog value from channel 2 and displays it on PORTB and PORTC include built in h unsigned int adc rd void main DDRB OxFF Set PORTB as output DDRC OxFF Set PORTC as output while 1 adc rd ADC Read 2 get ADC value from 2nd channel PORTB adc rd display 7 0 PORTC display 9 8 232 MIKROELEKTRONIKA SOFTWAR
258. W sa Rea A UHR AUR CR 35 Customizing IDE Layout 37 Docking Windows 37 Saving Layout 22 2 22 2 4 vega 4 38 Auto 39 Advanced Code 40 Advanced Editor Features 40 Code Assistant usse De RG es A ee we ee 41 Code Folding bid tee did oad ieee 42 Parameter Assistant 43 Code Templates Auto Complete 43 Auto Correct 43 Spell Checker 44 Bookmarks 222 ee 44 es ae Pe ea Pe are 44 Comment 44 Code Explorer 45 Routine List OR EAR UR LR AIR BR GR RR 46 Project Manager 47 Project Settings Window 49 Library 50 Error Window 52 Statistics ura bee eee ae A 53 Memory
259. _lnit routines MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 455 CHAPTER 6 Libraries mikroC PRO for AVR SPI Glcd Set X Sets x axis position to x pos dots from the left border of Glcd within the select ed side Parameters Description x pos position on x axis Valid values 0 63 Note For side x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see SPI Glcd Init routines PS SPI Glcd Read Data Returns One byte from Glcd memory 2 Reads data from the current location of Gled memory and moves to the next Description ication Glcd needs to be initialized for SPI communication see SPI_GIcd_lnit routines Glcd side x axis position and page should be set first See the functions SPI Glcd Set Side SPI Glcd Set X and SPI Glcd Set Page char data data SPI Glcd Read Data 456 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI Glcd Write Data Prototype void SPI Glcd Write Data char Ddata Nothing Writes one byte to the current location in Gled memory and moves to the next location Description Parameters pdata data to be written Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Glcd side x axis position and page should be set first See the functions
260. ad data and send not acknowledge signal tmp TWI Read 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 531 CHAPTER 6 Libraries mikroC PRO for AVR TWI Write Sends data byte parameter data_ via TWI bus TWI must be configured before using this function See TWI Init Also START signal needs to be issued in order to use this function See TWI Start Example Write 0xA3 TWI Stop or 2 Emme wen TWI Status Returns Returns value of status register TWSR the highest 5 bits exec TWI Close Closes TWI connection TWI must be configured before using this function See TWI Init LINIEN 532 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Library Example This code demonstrates use of TWI Library procedures and functions AVR MCU is connected SCL SDA pins to 24002 EEPROM Program sends data to EEPROM data is written at address 2 Then we read data via TWI from EEPROM and send its value to PORTA to check if the cycle was successful Check the figure below void main DDRA OxFF configure PORTA as output Init 100000 initialize TWI communication TWI Start issue TWI start signal TWI Write 0xA2 send byte via TWI device address 4 W TWI Write 2 send byte address of EEPROM location TWI Write 0xAA send data data to be
261. ad was successful or 1 if an error occurred Function reads one sector 512 bytes from MMC card at sector address Description sector Read data is stored in the array data Function returns 0 if read was successful or 1 if an error occurred Library needs to be initialized see Init Example rror Mmc Read Sector sector data MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 325 CHAPTER 6 Libraries mikroC PRO for AVR Mmc_Write_Sector 4 char Write Sector unsigned long sector char Prototype dbuff Returns 0 if write was successful returns 1 if there was an error in sending write command returns 2 if there was an error in writing Function writes 512 bytes of data to MMC card at sector address sector Func Description tion returns 0 if write was successful or 1 if there was an error in sending write command or 2 if there was an error in writing Requires Library needs to be initialized see Mmc Init Example error Mme Write Sector sector data Mmc_Read_Cid Prototype unsigned char Mmc Read Cid char data for registers Returns 0 if read was successful or 1 if an error occurred Function reads CID register and returns 16 bytes of content into data for reg isters Library needs to be initialized see Init Example error Mmc Read Cid data Mmc Read Csd Description Prototype unsigned char Mmc Read Csd char data for registers
262. al pin 6963 ctrlrst Direction Direction of Reset signal pin must be defined before using this function T6963C module connections char T6963C ctrlPort at FORTC char T6963C dataPort at PORTD char T6963C ctrlPort Direction at DDRC char T6963C dataPort Direction at DDRD sbit T6963C ctrlwr at PORTC B2 sbit T6963C ctrlrd at PORTC B1 sbit T6963C ctrlcd at PORTC BO sbit T6963C ctrlrst at PORTC B4 sbit T6963C ctrlwr Direction DDRC B2 sbit T6963C ctrlrd Direction at DDRC B1 sbit T6963C ctrlcd Direction at DDRC BO sbit T6963C ctrlrst Direction at DDRC B4 End of T6963C module connections init display for 240 pixel width 128 pixel height and 8 bits character width T6963C init 240 128 8 T6963C WriteData Prototype void T6963C WriteData unsigned char mydata Writes data to T6963C controller Description Parameters mydata data to be written Toshiba GLCD module needs to be initialized See the T6963C Init routine Example T6963C WriteData AddrL 510 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries T6963C_WriteCommand Prototype T6963C WriteCommand unsigned char mydata Writes command to T6963C controller Description Parameters nydata command to be written Toshiba GLCD module needs to be initialized See the T6963C Init routine 18 T6963C WriteCommand T6963C CURSOR POINTE
263. ar str unsigned char unsigned char y unsigned char mode Nothing Writes text in the current text panel of Glcd at coordinates x y Parameters str text to be written x text position on x axis y text position on y axis mode mode parameter Valid values SPI 6963 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 combin ing text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in nega tive mode i e white text on black background AND Mode The text and graphic data shown on the display are com bined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Toshiba Glcd module needs to be initialized See SPI T6963C Config routine 490 SPI T6963C Write Text Glcd LIBRARY D T6963C ROM MODE _EXOR MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI_T6963C_Line void SPI T6963C Line int x0 int
264. ar unsigned char c unsigned char x unsigned char y unsigned char mode Nothing Writes a char in the current text panel of Glcd at coordinates x y Parameters c char to be written x Char position on x axis y char position on y axis node mode parameter Valid values SPI 6963 ROM MODE OR SPI 6963 ROM MODE SPI 6963 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 combin ing text and graphics for example labels on buttons XOR Mode In this mode the text and graphics data are combined via the logical exclusive OR This can be useful to display text in nega tive mode i e white text on black background AND Mode The text and graphic data shown on display are combined via the logical AND function TEXT Mode This option is only available when displaying just a text The Text Attribute values are stored in the graphic area of display memory For more details see the T6963C datasheet Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example 521 T6963C Write Char A 22 23 AND MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 489 CHAPTER 6 Libraries mikroC PRO for AVR SPI_T6963C_Write_Text Prototype Description void SPI T6963C Write Text unsigned ch
265. are is owned by mikroElektronika Associates and is protected by copy right law and international copyright treaty Therefore you must treat this Software like any other copyright material e g a book You may transfer Software and documentation on a permanent basis provided You retain no copies and the recipient agrees to the terms of the License Agreement Except as provided in the License Agreement you may not transfer rent lease lend copy modify translate sublicense time share or electronically transmit or receive Software media or documentation You acknowledge that Software in the source code form remains a confidential trade secret of mikroElektronika Associates and therefore you agree not to modify Software or attempt to reverse engineer decompile or disassemble it except and only to the extent that such activity is expressly permitted by applicable law notwithstanding this limitation If you have purchased an upgrade version of Software it constitutes a single prod uct with the mikroElektronika Associates software that you upgraded You may use the upgrade version of Software only in accordance with the License Agreement 4 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroC PRO for AVR Introduction LIMITED WARRANTY Respectfully excepting the Redistributables which are provided as is without war ranty of any kind mikroElektronika Associates warrants that Software once
266. ari var2 are 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 register or the default auto Optional type qualifier can take values const Or volatile For more details refer to Storage Classes and Type Qualifiers For example Create 3 integer variables called x y and z and initialize x and y to the values 1 and 2 respectively int x 1 y 2 2 remains uninitialized Create a floating point variable q with static modifier and initialize it to 0 25 static float q 25 These are all defining declarations storage is allocated and any optional initializers are applied MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 179 CHAPTER 5 Language Reference mikroC PRO for AVR LINKAGE An executable program is usually created by compiling several independent trans lation 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 in the same scope The linkage is a process that allows each instance of an identifier
267. arted 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 93 CHAPTER 2 Environment mikroC PRO for AVR RAM Window The Software Simulator RAM Window is available from the drop down menu View Debug Windows RAM The RAM Window displays a map of MCU s RAM with recently changed items col ored red You can change value of any field by double clicking it 8 888 8 8 m o 888588588888 8888815 8888 sssssssssssssss s 8882s82252s5s58858558 s s s s 8ssssssssss 8 888 888 888 8 8 sja 8 s ssgsssssssssssss s 88888888888382382588 8 88888888888828288 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 2 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 sessssssssssssss s 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8888888858 94 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment SOFTWARE SIMULATOR OPTIONS Function Toolbar Description Key Icon Start Software Simulator F9 Run Pause Run or pause Software Simulator F6 ebugger Stop Software Simulator Ctrl F 2 Toggle breakpoint at the current cursor pos
268. ary routines Led module connections sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit LCD_RS CD EN LCD 4 Lob 05 LCD D6 LCD ng LCD_RS CD LCD LCD LCD at at at at at at PORTD 4 Boy PORTD BY PORTD PORTD PORTD PORTD Direotron EN Direction _D4_ Direction DS Direction DE Direction D7 Direction B2 B6 at DDRD B2 at DDRD B3 at DDRD B4 at DDRD B5 at DDRD B6 at DDRD B7 End LCD module connections char char char char char void EXEL x2 txt4 i mikroElektronika EasyAVR5A Led4bit example Move_Delay Delay ms 500 void main Moving text for i 0 Lcd Cmd LCD SHIFT RIGHT Move Delay i 4 Led Init Lcd Cmd LCD CLEAR Lcd Cmd LCD CURSOR OFF Led Out 1 6 txt3 Lcd Out 2 6 txt4 Delay ms 2000 Lcd Cmd LCD CLEAR Lcd Out 1 1 txt1 Lcd Out 2 4 txt2 Delay ms 2000 poX4 Loop variable CHAPTER 6 Libraries Function used for text moving You can change the moving speed here Initialize Lcd Clear Write Write Clear Write Write Move text display Cursor off text in text in display text in text in first row second row first row second row to the right 4 times MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOL
269. at 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 char acter and matches etc Examples unsigned matches string unsigned unsigned matches string unsigned Escape sequences Characters may be specified using a escape sequences n matches a newline c a tab etc More generally xnn where nn is a string of hexadecimal digits matches the character whose ASCII value is nn If you need wide Unicode character code you can use nnnn where nnnn one or more hexadecimal digits xnn Char with hex code nn Vx nnnn char with hex code nnnn one byte for plain text and two bytes for Unicode t tab HT TAB same as x09 Vn newline NL same as x0a vr car return CR same as xo form feed FF same as 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 PRO for AVR 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 enclo
270. at ww and store it to buffer UartWriteConstText r ng format Write message on UART UartWriteText buffer Write buffer on UART 572 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries TIME LIBRARY The Time Library contains functions and type definitions for time calculations in the UNIX time for mat which counts the number of seconds since the epoch This is very convenient for programs that work with time intervals the difference between two UNIX time values is a real time differ ence measured in seconds What is the epoch Originally it was defined as the beginning of 1970 GMT January 1 1970 Julian day GMT Greenwich Mean Time is a traditional term for the time zone in England The TimeStruct type is a structure type suitable for time and date storage Type declaration is contained in timelib h which can be found in the mikroC PRO for AVR Time Library Demo example folder Library Routines Time_dateToEpoch Time_epochToDate Time dateDiff Time dateToEpoch Prototype long Time dateToEpoch TimeStruct ts Returns Number of seconds since January 1 1970 OhOOmn00s This function returns the unix time number of seconds since January 1 1970 OhOOmn00s Besetiption Parameters ts time and date value for calculating unix time include timelib h TimeStruct tel long epoch JE what is the epoch of the date in ts Ay
271. atement Switch Statement Iteration Statements Loops While Statement Do Statement For Statement Jump Statements Break and Continue Statements Goto Statement Return Statement Compound Statements Blocks Preprocessor Introduction to Preprocessor Preprocessor Directives Macros File Inclusion Preprocessor Operators Conditional Compilation MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 121 CHAPTER 5 Language Reference mikroC PRO for AVR LEXICAL ELEMENTS OVERVIEW The following topics provide a formal definition of the mikroC PRO for AVR lexical elements They describe different categories of word like units tokens recognized by the mikroC PRO for AVR 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 PRO for AVR are derived from a series of operations performed on your programs by the compiler and its built in preprocessor WHITESPACE Whitespace is a collective name given to spaces blanks horizontal and vertical tabs newline characters and comments Whitespace can serve to indicate where tokens start and end but beyond this function any surplus whitespace is discarded For example two sequences int a7 float f and int i float f are lexically equivalent and parse identically to give six tokens Whitespace in Strings The ASCII characters representing whitespace can occur within strin
272. atement labels Preprocessor macros The recursive nature of the declarator syntax allows complex declarators You ll probably want to use typedefs to improve legibility if constructing complex objects Lvalues Lvalue is an object locator an expression that designates an object An example of lvalue expression is P 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 exam ple is not a modifiable lvalue A pointer to a constant be changed but its deref erenced value cannot Historically 1 stood for left meaning that lvalue could legally stand on the left the receiving end of an assignment statement Now only modifiable lvalues can legal ly stand to the left of an assignment operator For example if a and b are noncon stant integer identifiers with properly allocated memory storage they are both mod ifiable Ivalues and assignments such as a 1 and a bare legal Rvalues The expression a bis notlvalue a b ais illegal because the expression on the left is not related to an object Such expressions are sometimes called rvalues short for right values MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 143 CHAPTER 5 Language Reference mikroC PRO for AVR SCOPE AND VISIBILITY Scope The scope of an identifier is
273. ather than instruction Simple Assignment Operator For a common value assignment a simple assignment operator is used expressionl expression2 The expressioni is an object memory location to which the value of expression2 is assigned Operand expression has to be lvalue and expression2 can expression The assignment expression itself is not lvalue If expressionl and expression2 are 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 is expressionl op expression2 where can be one of binary operators amp 7 lt lt gt gt Thus we have 10 different compound assignment operators amp lt lt gt gt All of them associate from right to left Spaces sep arating 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 expressioni expression is the same as expressionl expressionl expression2 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 203 CHAPTER 5 Language Reference 204 mikroC PRO for A
274. atic 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 Set Port Expander s PORTA pull up resistors Expander Set PullUpsPOortA 0 OxFF 362 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Expander_Set_PullUpsPortB Prototype void Expander Set PullUpsPortB char ModuleAddress char Data The function sets Port Expander s PortB pull up down resistors Parameters Description 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 Requires Port Expander must be initialized See Expander Init Set Port Expander s PORTB pull up resistors Expander Set PullUpsPortB 0 OxFF Expander Set PullUpsPortAB void Expander Set PullUpsPortAB char ModuleAddress unsigned int PullUps Nothing The function sets Port Expander s PortA and PortB pull up down resistors Prototype Parameters ModuleAddress Port Expander hardware address see schematic at Description the bottom of this page PullUps data for
275. atl6 quick format instead of init routine if a formatting is needed if Mmc Fat Init reinitialize spi at higher speed SPI1 Init Advanced SPI MASTER SPI FCY DIV2 SPI LO LI ING MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 327 CHAPTER 6 Libraries mikroC PRO for AVR Mmc_Fat_QuickFormat Prototype Description Requires unsigned char Mmc Fat _QuickFormat unsigned char port unsigned char pin char mmc fat label 0 if MMC SD card was detected successfully formated and initialized 1 if FAT16 format was unseccessful 255 if MMC SD card was not detected Formats to FAT16 and initializes MMC SD card Parameters port chip select signal port address pin Chip select pin mmc fat label volume label 11 characters in length If less than 11 characters are provided the label will be padded with spaces If null string is passed volume will not be labeled Note This routine can be used instead or in conjunction with Mmc Fat Init rou tine Note If MMC SD card already contains a valid boot sector it will remain unchanged except volume label field and only FAT and ROOT tables will be erased Also the new volume label will be set The appropriate hardware SPI module must be previously initialized Pointer to appropriate SPI Read function SPI1 Init Advanced SPI MASTER ING Spi Rd Ptr SPI1 Read Format and initialize MMC SD
276. ators also known as separators Tokens can 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 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 postincrement operator addition operator b variable identifier statement terminator Note that parses as the longest token possible followed by According to the operator precedence rules our code sequence is actually inter 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 125 CHAPTER 5 Language Reference mikroC PRO for AVR CONSTANTS Constants or literals are tokens representing fixed numeric or character values The mikroC PRO for AVR supports integer constants floating point constants character constants string constants strings literals enumeration constants The data type of a constant is deduced by the compiler using such clues as a numeric value and format used in
277. ave been included Note Functions have been mostly implemented according to the ANSI C standard but certain functions have been modified in order to facilitate AVR 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 554 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries memchr Prototype void memchr void p char n unsigned int v Function locates the first occurrence of n in the initial v bytes of memory area starting at the address p The function returns the pointer to this location or O if the n was not found Description For parameter p you can use either a numerical value literal variable constant indicating memory address or a dereferenced value of an object for example amp mystring amp PO memcmp Prototype int memcmp void s1 void s2 int n Function compares the first characters of objects pointed to by 1 and s2 and returns zero if the objects are equal or returns a difference between the first dif Description fering characters in a left to right evaluation Accordingly the result is greater than zero if the object pointed to by s1 is greater than the object pointed to by s2 and vice ve
278. ax Highlighting Code Folding Code Assistant Parameters Assistant Auto Correct for common typos and Code Tem plates Auto Complete The Code Explorer with Keyboard shortcut browser and Quick Help browser is at your disposal for easier project management The Project Manager alows multiple project management General project settings can be made in the Project Settings window Library manager enables simple handling libraries being used in a project The Error Window displays all errors detected during compiling and linking The source level Software Simulator lets you debug executable logic step by step by watching the program flow MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 35 CHAPTER 2 Environment mikroC PRO for AVR The New Project Wizard is a fast reliable and easy way to create a project Help files are syntax and context sensitive Like in any modern Windows application you may customize the layout of mikroC PRO for AVR to suit your needs best Spell checker underlines identifiers which are unknown to the project In this way it helps the programmer to spot potential problems early much before the project is compiled Spell checker can be disabled by choosing the option in the Preferences dialog F12 36 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment CUSTOMIZING IDE LAYOUT Docking Windows You can inc
279. ay be different from chip to chip Please refer to datasheet before using flash library Note Currently Write operations are not supported See mikroC PRO for AVR specifics for details Library Routines FLASH_Read_ Byte FLASH_Read_Bytes FLASH_Read_Word FLASH_Read_Words FLASH_Read_Byte for MCUs with 64kb of Flash memory or less char FLASH Read Byte unsigned int address Prototype for MCUs with Flash memory larger than 64kb char FLASH Read Byte unsigned long address Returns Returns data byte from Flash memory Description Reads data from the specified address in Flash memory for MCUs with Flash memory larger than 64kb unsigned long tmp tmp Flash Read 0x0D00 278 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries FLASH_Read_Bytes for MCUs with 64kb of Flash memory or less void FLASH Read Bytes unsigned int address char buffer unsigned NoBytes Prototype for MCUs with Flash memory larger than 64kb void FLASH Read E T long address char buffer unsigned NoBytes Dasttiption Reads number of data bytes defined by NoBytes parameter from the specified P address in Flash memory to varibale pointed by buffer for MCUs with Flash memory larger than 64kb const long F_ADDRESS 0x200 unsigned int dat buff 32 FLASH Read Bytes F ADDRESS dat buff 64 FLASH Read Word for MCUs with 64kb of Flash memory or less c
280. b bit mask The function will clear bit 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 clear bits 0 1 on control port T6963C ClearBit 0x03 518 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries T6963C_SetBit Prototype void T6963C SetBit char Sets control port bit s T Parameters Description b bit mask The function will set bit x on control port if bit x in bit mask is set to 1 Toshiba GLCD module needs to be initialized See the T6963C Init routine set bits 0 and 1 on control port T6963C SetBit 0x03 T6963C NegBit Prototype T6963C NegBit char b Nothing Negates control port bit s eer Parameters Description b bit mask The function will negate bit x on control port if bit x in bit mask is set to 1 Toshiba GLCD module needs to be initialized See the 6963 routine negate bits 0 and 1 on control port T6963C NegBit 0x03 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 519 CHAPTER 6 Libraries mikroC PRO for AVR T6963C_DisplayGrPanel Prototype void T6963C DisplayGrPanel char n Display selected graphic panel Description Parameters n graphic panel number Valid values 0 and 1 Toshiba GLCD module needs to be initialized See the T6963C Ini
281. be in a mode in which receiving is possible See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page check the CANSPI module for received messages received do something char msg rcvd rx flags char data 8 long msg id If any was data len CANSPISetOperationMode CANSPI MODE NORMAL OxFF set NORMAL mode CANSPI module must be in mode in which receive is possible rx flags 07 clear message flags if msg rcvd CANSPIRead msg id data data len rx flags 242 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries CANSPIWrite Prototype Description MIKROELEKTRON char CANSPIWrite long id char wr data char data len char CAN TX MSG FLAGS 0 if all Transmit Buffers are busy OxFF if at least one Transmit Buffer is available 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 The CANSPI module must be in m
282. be issued in order to use this function See Soft I2C Start routine unsigned short take Read data and send the not acknowledge signal take Soft I2C Read 0 404 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Soft_I2C_Write Prototype unsigned short Soft I2C Write unsigned short Data b 0 if there were no errors 1 if write collision was detected on the lI C bus Sends data byte via the I C bus Description Parameters Data data to be sent Soft C must be configured before using this function See Soft I2C Init routine Also START signal needs to be issued in order to use this function See Soft I2C Start routine unsigned short data error error Soft I2C Write data error Soft I2C Write 0xA3 7 Soft I2C Stop Issues STOP signal Soft I2C must be configured before using this function See Soft I2C Init routine Issue STOP signal Soft I2C Stop MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 405 CHAPTER 6 Libraries mikroC PRO for AVR Soft I2C Break Description Requires All Software 12C Library functions can block the program flow see note at the top of this page Call this routine from interrupt to unblock the program execu tion This mechanism is similar to WDT Note Interrupts should be disabled before using Software 12C routins again see note at the top
283. bedded macro identifiers eligible for expansion Here is a simple example MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 221 CHAPTER 5 Language Reference mikroC PRO for AVR simple macro which returns greater of its 2 arguments define _MAX A B gt B A B Let s call it x MAX a c d Preprocessor will transform the previous line into x a 6 gt c d a b e d 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 undef 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 is undefined No macro expansion occurs within the undeg lines The state of being defined or undefined is an important property of an identifier regardless of the actual definition The ifdef and ifndef conditional directives used to test whether any identifier is currently defined or not offer a flexible 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 222 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Lan
284. below should be commented out ef define putString SPI Ethernet putString this function is called by the library the user accesses to the HTTP request by successive calls to Spi Ethernet _getByte the user puts data in the transmit buffer by successive calls to Spi Ethernet putByte the function must return the length in bytes of the HTTP reply or 0 if nothing to transmit if you don t need to reply to HTTP requests just define this function with a return 0 as single statement ixi MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 447 CHAPTER 6 Libraries mikroC PRO for AVR unsigned int SPI Ethernet UserTCP unsigned char remoteHost unsigned int remotePort unsigned int localPort unsigned int reqLength unsigned int len my reply length if localPort 80 I listen only to web request on port 80 return 0 get 10 first bytes only of the request the rest does not matter here for len 0 len lt 10 len getRequest len SPI Ethernet getByte 0 len 0 if memcmp getRequest httpMethod 5 only GET method is supported here return 0 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 replied by this request can be interpreted as javascript statements by
285. between graphic panel 0 and graphic 1 277 if PINAO 1 1 panel amp 1 SPI T6963C displayGrPanel panel Delay ms 300 If PORTA 1 is pressed display only graphic panel else if PINA1 SPI T6963C graphics 1 SPI T6963C text 0 Delay ms 300 If PORTA 2 is pressed display only text panel A else if PINA2 SPI T6963C graphics 0 SPI T6963C text 1 Delay ms 300 PORTA 3 is pressed display text and graphic panels else if PINA3 SPI T6963C graphics 1 SPI T6963C text 1 Delay ms 300 If PORTA 4 is pressed change cursor else if PINA4 2 if curs 3 curs 0 switch curs case 0 no cursor SPI T6963C cursor 0 break MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 503 CHAPTER 6 Libraries mikroC PRO for AVR case 1 blinking cursor SPI T6963C cursor 1 SPI T6963C cursor blink 1 break case 2 non blinking cursor SPI T6963C cursor 1 SPI T6963C cursor blink 0 break Delay ms 300 Move cursor even if not visible cposxt if cposx SPI T6963C txtCols cposx 0 j if cposy SPI T6963C grHeight SPI T6963C CHARACTER HEIGHT cposy 0 SPI T6963C set cursor cposx cposy Delay ms 100 504 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
286. breed ened d Ure edet dd 353 External dependencies of Port Expander Library 353 Library RoutineS 353 Expander EIER 354 Expander Read Byte 355 Expander Write Byte 355 Expander Read PortA 356 Expander Read PortB 356 Expander Read PortAB 357 Expander Write Port 358 Expander Write PortB 359 Expander Write PortAB 360 Expander Set DirectionPortA 361 Expander Set 361 Expander Set DirectionPortAB 362 Expander Set 362 Expander Set 363 Expander Set PullUpsPortAB 363 Library 364 HW Connection 365 PS 2 LIDAN i3 enira d ep bad Yeu ede teed 366 External dependencies of PS 2 366 Library Routines 22 22 aa Ee ae a ee YEAR 366 PS2 Conflg cesi
287. browsers len putConstString httpHeader HTTP header len putConstString httpMimeTypeScript with text MIME type add PORTC value buttons to reply len putConstString var PINC WordToStr PINC dyna len putString dyna len putConstString add PORTD value LEDs to reply len putConstString var PORTD WordToStr PORTD dyna len putString dyna len putConstString 448 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries add HTTP requests counter to reply WordToStr httpCounter 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 isdigit getRequest 6 if 0 bit num ber lt 9 bits 8 amp 9 does not exist but does not matter bitMask getRequest 6 0 convert ASCII to integer bitMask 1 lt lt bitMask create bit mask PORTD bitMask toggle PORTD with xor operator if len 0 what do to by default len putConstString httpHeader s HTTP header len putConstString httpMimeTypeHTML Ye with HTML MIME type len putConstString indexPage HTML page first part len putConstString indexPage2 HTML page second par
288. byte from Port Expander s PortA Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Port Expander must be initialized See Expander_Init Port Expander s PortA should be configured as input See Expander Set Direc tionPortA and Expander_Set_DirectionPortAB routines Read a byte from Port Expander s PORTA char read data Expander Set DirectionPortA 0 0xFF set expander s porta to be input read data Expander Read PortA 0 Expander Read PortB Prototype Expander Read PortB char ModuleAddress Description The function reads byte from Port Expander s PortB Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Port Expander must be initialized See Expander Init Port Expander s PortB should be configured as input See Expander Set Direc tionPortB and Expander Set DirectionPortAB routines Read a byte from Port Expander s PORTB char read data Expander Set DirectionPortB 0 0xFF set expander s portb to be input read data Expander Read PortB 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Expander_Read_PortAB Prototype unsigned int Expander Read PortAB char ModuleAddress The function reads word from Port Expander s ports PortA readings are in the higher byte of the result PortB reading
289. 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 V1 Pressure no hit dat2string SUM3 _vtext and here are some invalid identifiers temp 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 137 CHAPTER 5 Language Reference mikroC PRO for AVR PUNCTUATORS The mikroC PRO for AVR punctuators also known as separators are Brackets Parentheses Braces Comma Semicolon Colon Asterisk Equal sign Pound sign Most of these punctuators also function as operators Brackets Brackets indicate single and multidimensional array subscripts char ch str mikro int mati 3 4 3 x 4 matrix ch str 3 Ath element Parentheses Parentheses are used to group expressions isolate conditional expressions and indicate function calls and function paramet
290. cation The user must initialize the SPI module before using the SPI Lcd Library Note This Library is designed to work with the mikroElektronika s Serial Lcd Adapter Board pinout See schematic at the bottom of this page for details External dependencies of SPI Lcd Library The implementation of SPI Lcd Library routines is based on Port Expander Library routines Prior to calling any of this library routines Spi Rd Ptr needs to be initialized with the appropriate SPI Read routine External dependencies are the same as Port Expander Library external dependen cies Library Routines SPI Lcd Config SPI Lcd Out SPI Lcd Out Cp SPI Lcd Chr SPI Lcd Chr Cp SPI Lcd Cmd MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 469 CHAPTER 6 Libraries mikroC PRO for AVR SPI Lcd Config Prototype SPI Lcd Config char DeviceAddress Nothing Initializes the Lcd module via SPI interface Parameters Description DeviceAddress SPI expander hardware address see schematic at the bottom of this page Global variables SPExpanderCs Chip Select line SPExpanderRST Reset line SPExpanderCS Direction Direction of the Chip Select pin Requires SPExpanderRST Direction Direction of the Reset pin must be defined before using this function The SPI module needs to be initialized See SPI1 Init and SPI1 Init Advanced routines Port Expander mo
291. ch control is transferred when that function is 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 variable 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 is voia which really means a pointer to anything Pointers to voia are often called generic pointers and are treated as pointers to char in the mikroC PRO for AVR If type is any predefined or user defined type including voia 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 in this way if p is an object of type then p has to be a pointer to such object object of type Note You must initialize pointers before using them Our previously declared point er p is not initialized i e assigned a value so it cannot be used yet Note In case of multiple pointer declarations each identifier requires an indirect operator For example 158 MIKROELEKTRONIKA SOFTWARE AND HARDWARE
292. char CANSPI RX FILTER BITS 0x07 Use this to access filter bits CANSPI RX FILTER 1 0x00 CANSPI RX FILTER 2 CANSPI RX FILTER 3 0x02 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 INVALID MSG 0x10 Set if invalid else cleared CANSPI RX XTD FRAME 0x20 Set if XTD message else cleared CANSPI RX RTR 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 amp to adjust the appropriate flags For example if MsgFlag 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 Bl 0 CANSPI MASK B2 1 246 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries CANSPI_FILTER CANSPI FILTER constants define filter codes Functions CANSPISetFilter expects one of these as it s argument const char CANSPI FILTER Bl Fl 0 CANSPI FILTER Bl F2 1 CANSPI FILTER B2 Fl 2 CANSPI FILTER B2 F2 3 CANSPI FILTER B2 F3 4 CANSPI FILTER B2 F4 5 Library
293. control as the program executes In the absence of specific jump and selection statements statements are executed sequentially in the order of appearance in the source code Statements can be roughly divided into Labeled Statements Expression Statements Selection Statements Iteration Statements Loops Jump Statements Compound Statements Blocks Labeled Statements Each statement in a program can be labeled A label is an identifier added before the statement like this label identifier statement There is no special declaration of a label it just tags the statement Label identifier has a function scope and the same label cannot be redefined within the same function Labels have their own namespace label identifier can match any other identifier in the program A statement can be labeled for two reasons 1 The label identifier serves as a target for the unconditional goto statement 2 The label identifier serves as a target for the switch statement For this purpose only case and default labeled statements are used case constant expression statement default statement 208 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference EXPRESSION STATEMENTS Any expression followed by a semicolon forms an expression statement expression The mikroC PRO for AVR executes an expression statement by evaluating the expression All side effect
294. coordinate of the line start Valid values 0 63 x end X coordinate of the line end Valid values 0 127 y end y coordinate of the line end Valid values 0 63 color color parameter Valid values 0 2 Description Parameter color determines the line color 0 white 1 black and 2 inverts each dot Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Draw a line between dots 0 0 and 20 30 SPI Gled Line 0 0 20 30 458 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI_Glcd_V_Line void SPI Glcd V Line char y start char y end char x pos char color Draws a vertical line on Glcd Prototype Parameters y start y coordinate of the line start Valid values 0 63 DESCHBHOR y end y coordinate of the line end Valid values 0 63 x pos X coordinate of vertical line Valid values 0 127 color color parameter Valid values 0 2 Parameter color determines the line color 0 white 1 black and 2 inverts each dot Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Draw a vertical line between dots 10 5 and 10 25 SPI Glod V Line 5 25 10 1 SPI Glcd H Line void SPI Glcd H Line char x start char x end char y pos char color Draws a horizontal line on Glcd Prototype Parameters x start X coordinate of the line start Vali
295. cription set MAC multicast traffic will be disabled TICAST em CRC check flag When set CRC check will be 5 0x20 disabled and packets with invalid CRC field Ethernet CRC will be accepted cpewqewe DET MAC Unicast traffic receive filter flag When 5 Ethernet UNI set MAC unicast traffic will be disabled CAST Note Advance filtering available the Nc287360 module such as Pattern Match Magic Packet and Hash Table can not be disabled by this routine MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 437 CHAPTER 6 Libraries mikroC PRO for AVR Note This routine will change receive filter configuration on the fly It will not in Description the zNc28760 module The any way mess with enabling disabling receive transmit logic or any other part of ENC28J60 module should be properly cofigured by the means of SPI Ethernet Init routine Requires Ethernet module has to be initialized See SPI Ethernet Init SPI Ethernet Disable SPI Ethernet CRC SPI Ethernet UNICAST disable CRC checking and Unicast traffic SPI Ethernet doPacket Prototype unsigned char SPI Ethernet doPacket 0 upon successful packet processing zero packets received or received packet processed successfully 1 upon reception error or receive buffer corruption ENc28760 controller needs to be restarted 2 received packet was not sent to u
296. ctions MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 235 CHAPTER 6 Libraries mikroC PRO for AVR CANSPISetOperationMode Prototype Description void CANSPISetOperationMode char mode char WAIT Nothing Sets the CANSPI module to requested mode Parameters node CANSPI module operation mode Valid values CANSPI_OP MODE con stants 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 cor rect operation mode before performing mode specific operation If warT the call is blocking the function won t return until the requested mode is set The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page set the CANSPI module into configuration mode wait inside CANSPISetOperationMode until this mode is set CANSPISetOperationMode CANSPI MODE CONFIG OxFF CANSPIGetOperationMode Prototype char CANSPIGetOperationMode Returns Current operation mode Description The function returns current operation mode of the CANSPI module Check CANSPI OP MODE constants see CANSPI constants or device datasheet for ope
297. current text panel SPI T6963C SetTxtPanel 1 SPI T6963C PanelFill Prototype SPI T6963C PanelFill unsigned char v Nothing Fill current panel in full graphic text with appropriate value 0 to clear Description Parameters v value to fill panel with Toshiba Glcd module needs to be initialized See SPI 6963 Config routine clear current panel SPI T6963C PanelFill 0 SPI T6963C GrFill Prototype SPI T6963C GrFill unsigned char v Nothing Fill current graphic panel with appropriate value 0 to clear Description Parameters v Value to fill graphic panel with Toshiba Glcd module needs to be initialized See SPI T6963C Config routine clear current graphic panel SPI T6963C GrFill 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 497 CHAPTER 6 Libraries mikroC PRO for AVR SPI T6963C TxtFill Prototype void SPI T6963C TxtFill unsigned char v Fill current text panel with appropriate value 0 to clear Description Parameters v this value increased by 32 will be used to fill text panel Toshiba Glcd module needs to be initialized See SPI T6963C Config routine clear current text panel SPI T6963C TxtFill 0 SPI T6963C Cursor Height Prototype void SPI T6963C Cursor Height unsigned char n Set cursor size Description Parameters n cursor height Valid values 0 7 Toshiba Glcd module nee
298. d MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 159 CHAPTER 5 Language Reference mikroC PRO for AVR 160 FUNCTION POINTERS Function Pointers are pointers i e variables which point to the address of a func tion Define a function pointer int pt2Function float char char Note Thus functions and function pointers with different calling 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 is optional Assign an address to the function pointer int DoIt float a char b char c return atbtc pt2Function amp DoIt assignment Example int addC char x char y return xty 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference int modC char x char y return x y array of pointer to functions that receive two chars and returns int int arrpf char char addC subC mulC divC modC int res char i void main for 1 0 1 lt 5 1 res arrpf i 10 20 POINT
299. d Cid data for registers if i 0 for k 0 k lt 15 k printhex data for registers k if k 15 VARTI Write MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 337 CHAPTER 6 Libraries mikroC PRO for AVR UART1 Write 13 else UART1 Write Text CID error i Mmc Read Csd data for registers if i 0 for k 0 k 15 k printhex data_for registers k if k 15 VARTI Write UART1 Write 13 UART1 Write 10 else UART1 Write Text CSD error fendif Variables initialisation serial pointer 0 MAIN loop while 1 if UART1 Data Ready serial buffer serial pointer UART1 Read Get the received character serial pointer t if serial pointer serial pointer 0 Collecting four bytes of the address if serial buffer 0 S first byte serial buffer 1 if serial buffer 0 s second byte serial buffer 1 if serial buffer 0 E third byte serial buffer 1 if serial buffer 0 e fourth byte serial buffer 1 if serial buffer 0 R Command Read memmory if serial buffer 1 r sector address long first byte lt lt 24 long second byte lt lt 16 long third byte lt lt 8 long fourth byte i Mmc Read Sector sector address dData UART1 Write 0x30 i if i 0 338 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SO
300. d M Test File Exist unsigned long fsize unsigned int year unsigned short month day hour minute unsigned char outstr 12 filename 7 B uncomment this line to search for file that DOES exists filename 7 F uncomment this line to search for file that DOES NOT exist if Cf Fat Assign filename 0 file has been found get its date Cf Fat Get File Date amp year amp month amp day amp hour amp minute WordToStr year outstr I Write Str outstr ByteToStr month outstr I Write Str outstr WordToStr day outstr I Write Str outstr WordToStr hour outstr I Write Str outstt WordToStr minute outstr I Write Str outstr get file size fsize Cf Fat Get File Size LongToStr signed long fsize outstr I Write Str outstr else file was not found signal it UART1 Write 0x55 Delay ms 1000 UART1 Write 0x55 Tries to create a swap file whose size will be at least 100 sectors see Help for details void M Create Swap File unsigned int i for i 0 i 512 i Buffer i i 272 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR CHAPTER 6 Libraries size Cf Fat Get Swap File 5000 mikroE txt 0x20 see help on this function for details if size LongToStr signed long size fat txt I Write Str fat txt 1 0 i 5000 i
301. d above For example 0777 will be treated as int 128 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference FLOATING POINT CONSTANTS A floating point constant consists of Decimal integer Decimal point Decimal fraction e or E and a signed integer exponent optional Type suffix or F or 1 or L optional Either decimal integer or decimal fraction but not both can be omitted Either dec imal point or letter e or E with a signed integer exponent but not both can be omit ted These rules allow conventional and scientific exponent notations Negative floating constants are taken as positive constants with an unary operator minus prefixed The mikroC PRO for AVR limits floating point constants to the range 1 17549435082 10 38 6 80564774407 1038 Here are some examples 0 0 0 1 23 1 23 23 45e6 23 45 10 6 2e 5 2 0 10 5 3E 10 3 0 10 10 09E34 0 09 10 34 The mikroC PRO for AVR floating point constants are of the type double Note that the mikroC PRO for AVR 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 PRO for AVR CHARACTER CONSTANTS A character constant is one or more characters enclo
302. d anywhere in the code Identifiers 80 57 are not case sensitive and have a specific namespace You may override them with your own members 80 87 within any given structure 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 sbit type The mikroC PRO for AVR compiler has sbit data type which provides access to bit addressable SFRs For example sbit LEDA at PORTA BO sbit name at sfr name B bit position The previously declared SFR sfr name is the base address for the sbit The bit position which must be a number from 0 7 follows the dot symbol and speci fies the bit position to access For example sbit OV at SREG B2 sbit CY at SREG B7 100 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroC PRO for AVR Specifics bit type The mikroC PRO Compiler provides a bit data type that may be used for variable declarations It can not be used for argument lists and function return values bit bf bit variable There are no pointers to bit variables bit pte invalid An array of type bit is not valid bites ete invalid Note Bit variables can not be initialized Bit variables can not be members of structures and unions Bit variables do not have addresses therefore unary operator amp address of is not applicable to these
303. d 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 lt type definition gt synonym The typedef keyword assigns synonym to lt type definition gt The synonym needs to be a valid identifier A declaration starting with the typedef specifier does not introduce an object or a function of a given type but rather a new name for a given type In other words the typedef declaration is identical to a normal declaration but instead of objects it declares types It is a common practice to name custom type identifiers with start ing capital letter this is not required by the mikroC PRO for AVR 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 In the typedef declaration as in any other declaration several types can be declared at once For example typedef int Pti Array 10 Here Pti is a synonym for type pointer to int and Array is a synonym for type array of 10 int elements 184 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference ASM DECLARATION The mikroC PRO for AVR allows embedding assembly in the source code by means of the asm declaratio
304. d values 0 127 Description x end X coordinate of the line end Valid values 0 127 y pos y coordinate of horizontal line Valid values 0 63 color color parameter Valid values 0 2 The parameter color determines the line color 0 white 1 black and 2 inverts each dot Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Draw a horizontal line between dots 10 20 and 50 20 SPI Gled H Line 10 50 20 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 459 CHAPTER 6 Libraries mikroC PRO for AVR SPI Glcd Rectangle void SPI Glcd Rectangle char x upper left char y upper left char x bottom right char y bottom right char color Nothing 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 bottom right x coordinate of the lower right rectangle corner Valid values Description 9 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 Draw a rectangle between dots 5 5 and 40 40 SPI Gled Rectangle 5 5 40 40
305. d waits for a response The Slave accepts data increments it and sends it back to the Master Master then does the same and sends incre mented data back to Slave etc Master displays received data on PO while error on receive OxAA and number of consecutive unsuccessful retries are displayed on P1 Slave displays received data on PO while error on receive 0xAA is displayed on P1 Hardware configurations in this example are made for the EasyAVR5 board 16 RS485 Master code 396 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries char dat 10 buffer for receving send ing messages char i j sbit RS485 rxtx pin at PORTD B2 set transcieve pin sbit RS485 rxtx pin direction at DDRD B2 set transcieve pin direction Interrupt routine void interrupt org 0x16 RS485Master Receive dat void main long cnt 0 PORTA 0 clear PORTA PORTB 0 clear PORTB PORTC 0 clear PORTC DDRA OxFF set PORTA as output DDRB OxFF set PORTB as output DDRC OxFF set PORTB as output Pass pointers to UART functions of used UART module UART Wr Ptr UART1 Write UART Rd Ptr UART1 Read UART Ptr UARTI1 Data Ready UART TX Idle UART1 TX Idle UART1 Init 9600 initialize UART1 module Delay ms 100 RS485Master Init initialize MCU as Master dat 0 OxAA dat 1 OxF0 2 Ox0
306. de 434 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR CHAPTER 6 Libraries The appropriate hardware SPI module must be previously initialized Global variables SPT SPI Requires Ethernet RST Reset line Ethernet CS Chip Select line Ethernet CS Direction Direction of the Chip Select pin Ethernet RST Direction Direction of the Reset pin must be defined before using this function def def m sfr sfr sfr sfr unsigned char myMacAddr 6 Doa ine SPI Ethernet HA ine SPI Ethernet FU FDUPLE LDUPLE E ethernet NIC pinout sbit SPI Ethernet Rst at PORTB B4 sbit SPI Ethernet CS at PORTB B5 sbit SPI Ethernet Rst Direction at DDRB B4 sbit SPI Ethernet CS Direction at DDRB B5 end ethernet NIC definitions my MAC address unsigned char myIpAddr addr Init Spi Rd Ptr of u SPI 1 SPI 1 SPI1 Read sed SPI module Ethernet Init amp PORTC 0 Ethernet FULLDUPLEX 0x00 0 14 0 5 0x76 192 169 1 60 0x19 Ox3f my IP pass pointer to SPI Read function amp PORTC 1 myMacAddr myIpAddr MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 435 CHAPTER 6 Libraries mikroC PRO for AVR SPI_Ethernet_Enable Description 436 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD
307. device over the OneWire bus Reads one byte of data via the OneWire bus Devices compliant with the Dallas OneWire protocol Global variables Requires OW Bit Read OneWire read line OW Bit Write OneWire write line OW Bit Direction Direction of the OneWire pin must be defined before using this function Read a byte from the One Wire Bus unsigned short read data read data Ow Read Ow Write Writes one byte of data via the OneWire bus Description Parameters data data to be written Devices compliant with the Dallas OneWire protocol Global variables OW Bit Read OneWire read line OW Bit Write OneWire write line OW Bit Direction Direction of the OneWire pin must be defined before using this function Send a byte to the One Wire Bus Ow Write 0xCC MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 349 CHAPTER 6 Libraries mikroC PRO for AVR Library Example This example reads the temperature using DS18x20 connected to pin PORTB 2 After reset MCU obtains temperature from the sensor and prints it on the LCD Make sure to pull up PORTB 2 line and to turn off the PORTB leds LCD module connections sbit LCD RS at PORTD B2 sbit LCD EN at PORTD B3 sbit LCD D4 at PORTD B4 sbit LCD D5 at PORTD B5 sbit LCD D6 at PORTD B6 sbit LCD D7 at PORTD B7 sbit LCD RS Direction at DDRD B2 D sbit LCD EN Direction at DDRD B3 sbit LCD D4 Direction at
308. displaying on Glcd Glcd needs to be initialized see Glcd Init routine Draw image my image on Glcd Glcd Image my image Library Example The following example demonstrates routines of the Glcd library initialization clear pattern fill image displaying drawing lines circles boxes and rectangles text displaying and handling Declarations const code char truck bmp 1024 Glcd module connections char char sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit sbit G LC LC LC LC LC LC D D 51 at D CS2 at D RS at D RW at EN at LC LC LC LC LC D ee sie D RST at A2HAAHAA LC PORTD PORTD POR PORTD POR PORTD Direction D CS2 Direction D RS Direction D RW Direction EN Direction D RST Direction B2 4 B6 B7 at at at at at at D DataPort at PORTC D DataPort Direction at DDRD DDRD DDRD DDRD End Glcd module connections DDRC B2 B3 B5 DDRD DDRD B6 B7 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 295 CHAPTER 6 Libraries mikroC PRO for AVR void delay28S 2 seconds delay function Delay ms 2000 void main unsigned short ii char someText Glcd Init Initialize Glcd Glcd Fill 0x00 Clear Glcd while 1 Glcd Image truck bmp
309. ds to be initialized See SPI T6963C Config routine SPI_T6963C_Graphics Prototype SPI T6963C Graphics char n Enable disable graphic displaying er Parameters Description n graphic enable disable parameter Valid values 0 disable graphic dispaying and 1 enable graphic displaying Toshiba Glcd module needs to be initialized See SPI T6963C Config routine enable graphic displaying SPI 6963 Graphics 1 498 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI_T6963C_Text Prototype void sPI T6963C Text char n Nothing Enable disable text displaying Parameters Description n text enable disable parameter Valid values o disable text dispaying and 1 enable text displaying Toshiba Glcd module needs to be initialized See SPI T6963C Config routine enable text displaying SPI T6963C Text 1 SPI T6963C Cursor Prototype SPI T6963C Cursor char n Nothing Set cursor on off Description Parameters n on off parameter Valid values 0 set cursor off and 1 set cursor on Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set cursor on SPI T6963C Cursor 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 499 CHAPTER 6 Libraries mikroC PRO for AVR SPI T6963C Cursor Blink Prototype
310. dule connections sbit SPExpanderRST at PORTB BO0 sbit SPExpanderCS at PORTB B1 sbit SPExpanderRST Direction at DDRB BO sbit SPExpanderCS Direction at DDRB B1 End Port Expander module connections void main If Port Expander Library uses SPI1 module SPIL Inst Initialize SPI module used with PortExpander SPI Rd Ptr SPI1 Read Pass pointer to SPI Read function of used SPI module SPI Lcd Config 0 initialize Lcd over SPI interface 470 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI Lcd Out Prototype void SPI Lcd Out char row char column char text yp Prints text on the Lcd starting from specified position Both string variables and literals can be passed as a text Parameters Description row Starting position row number column starting position column number text text to be written Lcd needs to be initialized for SPI communication see SPI Lcd Config routines Write text Hello on Lcd starting from row 1 column 3 SPI Led Out l 3 Hello SPI Lcd Out Cp Prints text on the Lcd at current cursor position Both string variables and literals can be passed as a text Description Parameters text text to be written Requires Lcd needs to be initialized for SPI communication see SPI Lcd Config routines Write text Here at current cursor position SPI Lcd Out CP Here
311. e Note Check the AVR Specifics for more information on functions limitations on the AVR compliant micros Function Declaration Functions are declared in user s source files or made available by linking precom piled libraries The declaration syntax of the function is type function name parameter declarator list The function name must be a valid identifier This name is used to call the 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 voia is also allowed The function cannot return an array or another function MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 187 CHAPTER 5 Language Reference mikroC PRO for AVR Within parentheses parameter declarator list is a list of formal arguments that function takes These declarators specify the type of each function parameter The compiler uses this information to check validity of function calls If the list is empty a function does not take any arguments Also if the list is voia a function also does not take any arguments note that this is the only case
312. e 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 the mikroC PRO for AVR compiler you agree to the terms of this agreement Only one person may use licensed version of mikroC PRO for AVR compiler at a time Copyright mikroElektronika 2003 2008 This manual covers mikroC PRO for AVR version 1 23 and the related topics Newer ver sions may contain changes without prior notice COMPILER BUG REPORTS The compiler has been carefully tested and debugged It is however not possible to guarantee a 100 error free product If you would like to report a bug please contact us at the address office mikroe com Please include next information in your bug report Your operating system Version of mikroC PRO for AVR Code sample Description of a bug CONTACT US mikroElektronika Voice 381 11 36 28 830 Fax 381 11 36 28 831 Web www mikroe com E mail office mikroe com Windows is a Registered trademark of Microsoft Corp All other trade and or services marks are the property of the respective owners MIKRO
313. e SPI 6963 Config routine display graphic panel 1 SPI T6963C DisplayGrPanel 1 SPI T6963C DisplayTxtPanel Prototype void SPI T6963C DisplayTxtPanel char n Nothing Display selected text panel Description Parameters n text panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine display text panel 1 SPI T6963C DisplayTxtPanel 1 SPI T6963C SetGrPanel Prototype void SPI T6963C SetGrPanel char n Nothing Compute start address for selected graphic panel and set appropriate internal point ers All subsequent graphic operations will be preformed at this graphic panel Description Parameters n graphic panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example set graphic panel 1 as current graphic panel SPI T6963C SetGrPanel 1 496 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI_T6963C_SetTxtPanel Prototype void 5 6963 SetTxtPanel char n Nothing Compute start address for selected text panel and set appropriate internal point ers All subsequent text operations will be preformed at this text panel Description Parameters n text panel number Valid values 0 and 1 Toshiba Glcd module needs to be initialized See SPI T6963C Config routine set text panel 1 as
314. e Toolbar Project Manager Project Settings 84 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment CLEAN PROJECT FOLDER Clean Project Folder This menu gives you option to choose which files from your current project you want to delete vj Below is the list of all files in the project folder Files in bold are those generated by the compiler and they can be easily recreated when the project is rebuilt Select which files you want to remove from the project folder Please note that selected files will be permanently deleted from your disk if 7 SpiEthernet asm SpiEthernet c E SpiEthernet c ini SpiEthernet cp SpiEthernet dbg i SpiEthernet dct V SpiEthernet dlt E SpiEthernet hex SpiEthernet Ist SpiEthernet mcl SpiEthernet mcpav SpiEthernet mcproj_callertable txt SpiEthernet mil SpiEthernet user dic Clean Cancel C Program Files Mikroelektronika mikroC PRO for AVRX MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 85 CHAPTER 2 Environment mikroC PRO for AVR 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 D from the Project Toolbar If more more than one project is open you can compile all open projects by selecting Project gt Build All from the drop down menu or click the
315. e from the mikroC PRO for AVR terminal for RS 232 communication menu choice Tools Terminal char uart rd void main UART1 Init 9600 initialize UART module at 9600 bps Delay_ms 100 wait for UART module to stabilize while 1 endless loop if UART1 Data Ready if data is received uart rd UART1 Read read the received data UART1_ Write uart rd and send data via UART 540 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries HW Connection PC SUB D 9p f CONNECT Receive MCU TO PC data Rx 4 2 gt SERIAL gt e CABLE A Es TUNIS Bx i iU Send PC TO MCU TES 2 Data Tx SUB D 9p Q 22 VCCoO OSCILLATOR 1 10uF VCC Re H V 1 H 16 vec mm L2 y vst eno 15 L c1 nou 4 MN Tx 10uF rinj 5 Hoz 12 6 8 10 NS R2IN R20uT 10uF mpm RS 232 HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 541 CHAPTER 6 Libraries mikroC PRO for AVR ANSI C CTYPE LIBRARY The mikroC PRO for AVR provides a set of standard ANSI C
316. e variables strings Values are updated as you go through the simulation Recently changed items are colored red for variable by assembly name FARG_T6963C_circle 4 V Peripherals Freeze 92 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment Double clicking a variable or clicking the Properties Button 5 Properties opens the Edit Value window in which you can assign a new value to the selected variable register Also you can choose the format of variable register representation between decimal hexadecimal binary float or character All representations except float are unsigned by default For signed representation click the check box next to the Signed label An item s value can be also changed by double clicking item s value field and typing the new value directly 3 Edit Value ACD 83 0100 0000 1000 0011 0001 0010 0110 1111 Representation Dec Hex Bin Float Char Stopwatch Window The Software Simulator Stopwatch Window is available from the drop down menu View Debug Windows Stopwatch The Stopwatch Window displays a current count of cycles time since the last Soft ware Simulator action Stopwatch measures the execution time number of cycles from the moment Software Simulator has started and can be reset at any time Delta represents the number of cycles between the lines where Software Simulator action has st
317. early much before the project is compiled Spell checker can be disabled by choosing the option in the Preferences dialog F12 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 PRO for AVR FILE MENU OPTIONS The File menu is the main entry point for manipulation with the source files New Unit Ctrl N Ctrl 0 Ctrl 5 Close Ctrl F4 Print Ctrl P Exit Alt X File Description Save the active source file with the different name or change the file type Print Ctrl P Print Preview exit Alex Exit IDE Related topics Keyboard shortcuts File Toolbar Managing Source Files 14 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR EDIT MENU OPTIONS Undo Ctrl Z Redo Shift Ctrl Z Cut Ctrl X Copy Ctrl C Paste Ctrl Delete Select All Ctrl 4 Find Ctrl F Find Next F3 Find Previous Shift F3 Replace Ctrl R Find In Files Alt F3 Goto Line Ctrl G Advanced CHAPTER 2 Environment Edit Description Ctrl Z Undo last change Shift Ctrl Z Redo last change Ctrl Cut selected text to clipboard Ctrl C Copy selected text to clipboard Ct
318. ed 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 Applied 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 is the total number of bytes in the array in other words an array name is not converted to a pointer type int i j a 10 jx sizeof 1 j sizeof int 2 i sizeof a 1 l0 sizeof int 20 To get the number of elements in an array int num elem i j 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 205 CHAPTER 5 Language Reference mikroC PRO for AVR Expressions Expression is a sequence of operators operands and punctuato
319. en MCUs MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 189 CHAPTER 5 Language Reference mikroC PRO for AVR FUNCTION CALLS AND ARGUMENT CONVERSIONS Function Calls A function is called with actual arguments placed in the same sequence as their matching formal parameters Use the function call operator function name expression 1 expression n Each expression in the function call is an 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 is initialized by the expression of the return statement This means that the function call as an operand in complex expression is treated as a function result If the function has no result type void or the result is not needed then the func tion 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 for ma
320. ence 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 type Parentheses are mandatory For example Let s have two variables of char type char a b Following line will coerce 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 177 CHAPTER 5 Language Reference mikroC PRO for AVR DECLARATIONS A declaration introduces one or several names to a program it informs the compil er what the name represents what its type is what operations are allowed with it etc This section reviews concepts related to declarations declarations definitions declaration specifiers and initialization The range of objects that can be declared includes Variables Constants Functions Types Structure union and enumeration tags Structure members Union members Arrays of other types Statement labels Preprocessor macros 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 initializa
321. ents time based activities so interrupts need to be disabled when using it MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 313 CHAPTER 6 Libraries mikroC PRO for AVR External dependencies of Manchester Code Library The following variables must be defined in all projects using Description Manchester Code Library as sbit MANRXPIN extern sfr sbit MANRXPIN Receive line PINB B0 sbit MANTXPIN at extern sfr sbit MANTXPIN Transmit line PORTB Bl i bit extern sfr sbit Direction of the MANRXPIN Direction Recei i eceive at DDRB BO 44 5 of the IANTXPIN Direction Direction ransmit pin DDRB B1 Library Routines Man Receive Init Man Receive Man Send Init Man Send Man Synchro Man Break The following routines are for the internal use by compiler only Manchester 0 Manchester 1 Manchester Out 314 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Man_Receive_Init Prototype unsigned int Man Receive Init 0 if initialization and synchronization were successful 1 upon unsuccessful synchronization 255 upon user abort The function configures Receiver pin and performs synchronization procedure in order to retrieve baud rate out of the incoming signal Description Note In case of multiple persistent errors on reception
322. eparates variable declarations from initialization lists int test 5 1 2 3 4 5 int x 5 Equal sign is also used as an assignment operator in expressions 140 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference ine ay Dy G8 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 asso ciated with a code generation See the Preprocessor Directives for more informa tion and are also used as operators to perform token replacement and merging dur ing the preprocessor scanning phase See the Preprocessor Operators MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 141 CHAPTER 5 Language Reference mikroC PRO for AVR CONCEPTS This section covers some basic concepts of language essential for understanding of how C programs work First we need to establish the following terms that will be used throughout the help Objects and lvalues Scope and Visibility Name Spaces Duration OBJECTS An object is a specific region of memory that can hold a fixed or variable value or set of values This use of a term object is different from the same term used in object oriented languages which is more general Our defini
323. er als can be passed as a text mS Parameters Description row Starting position row number column Starting position column number text text to be written Requires The Lcd module needs to be initialized See Lcd Init routine Example Write text Hello on Lcd starting from row 1 column 3 Lod Out 1 3 Hello Lcd Out Cp Prototype Lcd Out Cp char text Nothing Prints text on Lcd at current cursor position Both string variables and literals can be passed as a text Parameters text text to be written Requires The Lcd module needs to be initialized See Lcd Init routine Example Write text Here at current cursor position Lcd Out Cp Here 308 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Lcd Chr Prototype void Lcd Chr char row char column char out char Nothing Prints character on Lcd at specified position Both variables and literals can be passed as a character Parameters Description row Writing position row number column Writing position column number out char character to be written Requires The Lcd module needs to be initialized See Lcd Init routine Write character i at row 2 column 3 Led Chr 2 3 Lcd Chr Cp Prototype Lcd Chr out char Nothing Prints character on Lcd at current
324. er 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 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 from the File Toolbar and name it as you want If you use the New Project Wizard an empty source file named after the project with extension will be created automatically The mikroC PRO for AVR does not require you to have a source file named the same as the project it s just a matter of convenience Opening an existing file 1 Select File Open from the drop down menu or press Ctrl O or click the Open File Icon v 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 MIKROELEKTRONI
325. erent type if an operator requires an operand of particular type and we use an operand of different type if a function requires a formal parameter of particular type and we pass it an object of different type if an expression following the keyword return does not match the declared function return type if intializing an object in declaration with an object of different type In these situations compiler will provide an automatic implicit conversion of types without any 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 174 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference STANDARD CONVERSIONS Standard conversions are built in the mikroC PRO for AVR These conversions are performed automatically whenever required in the program They can also be explicitly required by means of the typecast operator refer to the Explicit Typecast ing The basic rule of automatic implicit conversion is that the operand of simpler type is converted promoted to the type of more complex operand Then the type of the result is that of more complex operand Arithmetic Conversions When using arithmetic expression such as a b where a and b are of different arithmetic types the mikroC PRO for AVR performs implicit type conversions before
326. ers d c a b override normal precedence if d z x essential with conditional statement func function call no args void func2 int n function declaration with parameters Parentheses are recommended in macro definitions to avoid potential precedence problems during an expansion define CUBE x x x x For more information refer to Operators Precedence And Associativity and Expres sions 138 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference Braces Braces indicate the start and end of a compound statement if d z dies func Closing brace serves as a terminator for the compound statement so a semicolon is not required after except in structure declarations Sometimes the semicolon can be illegal as in if statement L sere HR illegal semicolon else Do For more information refer to the Compound Statements Comma Comma separates the elements of a function argument list void unc int n float f char ch Comma is also used as an operator in comma expressions Mixing two uses of comma is legal but you must use parentheses to distinguish them Note that exp1 exp2 evalutates both but is equal to the second fune i J call func with two args func expl exp2 exp3 exp4 exp5 also calls func with two args Semicolon Semicolon is a sta
327. es contained in tsil and ts2 buffers 74 diff Time dateDiff amp tsl amp ts2 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 575 CHAPTER 6 Libraries mikroC PRO for AVR Library Example This example demonstrates Time Library usage include timelib h TimeStruct tsl ts2 long epoch long diff void main tsl ss 0 tsl mn 7 tsl hh 17 tsl md 23 tsl mo 5 tsl yy 2006 y What is the epoch of the date in ts ay poch Time dateToEpoch amp tsl What date epoch 1234567890 1234567890 Time epochToDate epoch amp ts2 How much seconds between this two dates diff Time dateDiff amp tsl amp ts2 576 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries TRIGONOMETRY LIBRARY The mikroC PRO for AVR implements fundamental trigonometry functions These functions are implemented as look up tables Trigonometry functions are implemented in integer format in order to save memory Library Routines sinE3 cosE3 sinE3 Prototype sinE3 unsigned angle deg The function returns the sine of input parameter The function calculates sine multiplied by 1000 and rounded to the nearest integer result round sin angle deg 1000 Description Parameters angle deg input angle in degrees Note Return value
328. es in tree mh Locate declaration in code MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 45 CHAPTER 2 Environment mikroC PRO for AVR ROUTINE LIST Routine list diplays list of routines and enables filtering routines by name Routine list window can be accessed by pressing Ctri L You can jump to a desired routine by double clicking on it 46 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment PROJECT MANAGER Project Manager is IDE feature which allows users to manage multiple projects Several projects which together make project group may be open at the same time Only one of them may be active at the moment Setting project in active mode is performed by double click on the desired project in the Project Manager 4 2 LedBlinking mcpav 4 7 Sources 2 LedBlinking c 7j Header Files C Binaries 5 Project level defines E Image Files 4 Output Files ES LedBlinking hex LedBlinking asm LedBlinking lst Other Files Following options are available in the Project Manager MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 47 CHAPTER 2 Environment mikroC PRO for AVR Description Save project Group Open project group Close the active project Close project group Add project to the project group Remove project
329. escription 32 otherwise returns zero islower Prototype Prototype int islower char character Function returns 1 if the character is a lowercase letter a z otherwise returns Description zero ispunct D stHptlon Function returns 1 if the character is a punctuation decimal 32 47 58 63 91 P 96 123 126 otherwise returns zero isspace Prototype unsigned short isspace char character Function returns 1 if the character is a white space space tab CR HT VT NL FF otherwise returns zero Description isupper Prototype unsigned short isupper char character Function returns 1 if the character is an uppercase letter A Z otherwise Description returns zero isxdigit Prototype unsigned short isxdigit char character Function returns 1 if the character is a hex digit 0 9 A F a f otherwise returns zero Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 543 CHAPTER 6 Libraries mikroC PRO for AVR toupper Prototype unsigned short toupper char character er If the character is a lowercase letter a z the function returns an uppercase Description letter Otherwise the function returns an unchanged input parameter tolower Prototype unsigned short tolower char character If the character is an uppercase letter 2 function returns a lowercase letter Description Otherwise function returns a
330. escription projects using Button library extern sbit Declares button bins sbit Button Pin at Button Pin chile u p PINB BO 2 sbit extern sbit Declares direction of the Butt Pi Di ti butt Button Pun Direction utton Pin Direction utton at DDRB BO Library Routines Button MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 559 CHAPTER 6 Libraries Button Prototype Description mikroC PRO for AVR unsigned short Button unsigned short time unsigned short active state 255 if the pin was in the active state for given period 0 otherwise 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 1 logical one Global variables Button Pin Button pin line Button Pin Direction Direction of the button pin must be defined before using this function On every PBO one to zero transition PORTC is inverted Button connections sbit Button Pin at PINB BO Input pin PINx register is used sbit Button Pin Direction at DDRB B0 End Button connections bit oldstate Old s
331. essor increased by one Variables of the enum type are declared the same as variables of any other type For example the following declaration enum colors black red green blue violet white c establishes a unique integral type enum colors variable c of this type and set of enumerators with constant integer values black 0 red 1 In the mikroC PRO for AVR a variable of an enumerated type can be assigned any value of the type int no type checking beyond that is enforced That is c red OK i m dus 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 initializers 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 enum colors black value 0 red value 1 green value 2 blue 6 value 6 violet value 7 white 4 value 4 152 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference Initializer expression can include previously declared enumerators For example in the following declaration enum memory sizes bit 1 nibble 4 bit byte 2 nibble kilobyte 1024 byte nibble would acquire the
332. et 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 22 Fill out the registration form figure below select your distributor and click the Send button 8 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroC PRO for AVR Introduction Step 1 Fill in the form below Please make sure you fill in all required fields Step 2 Make sure that you provided a valid email address in the EMAIL edit box This email will be used for sending you the activation key Step 3 Make sure you select a correct distributor which will make the registration process faster If your distributor is not on the list then select Other and type in distributor s email address in the box below Step 4 Press the SEND button to send key request A default email client will open with ready to send message Note If email client does not open you may text of the message and paste it manually into a new email message before sending it to your distributor s email IM 515C 557269 6F6D72 684F i Krog k vv 1 have made the payment and I wish to request activation key for mikroC PRO for AVR Marko Jovanovic ey 515C 557269 6F6D72 684F Distributor Copy to Cancel dipboard This
333. eter Default value 8MHz used Specified search path does not exist 5 Specified include path does not exist 3 Result is not defined in function 551 Initialization of extern object 551 Suspicious pointer conversion Implicit conversion of pointer to int Unknown pragma line ignored 5 Implicit conversion of int to ptr Generated baud rate is s bps error s percent Illegal file type 55 Linker Error Messages Redefinition of 5 already defined in main function is not defined System routine is not found for initialization of 251 Bad agregate definition 5 Unresolved extern 3 Bad function absolute address 551 Not enough RAM s 90 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment SOFTWARE SIMULATOR OVERVIEW The Source level Software Simulator is an integral component of the mikroC PRO for AVR environment It is designed to simulate operations of the AVR 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 Simu lator by selecting Run Start Debugger from the drop down menu or by clicking the Start Debugger Icon ey from the Debugger Toolbar Starting the Software Simulator makes more options available Step Into Step Over Step Out Run to Cursor etc Line that is to be executed is c
334. eturn the result Returned value will be automat ically converted to the expected function type if needed The expression is option al 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 COMPOUND 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 For example the for loop expects one statement in its body so we can pass it a compound statement for i 2 lt nj atte d int temp ali bil bl i temp Note that unlike other statements compound statements do not end with semicolon i e there is never a semicolon following the closing brace MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 217 CHAPTER 5 Language Reference mikroC PRO for AVR PREPROCESSOR Preprocessor is an integrated text processor which prepares the source code for compiling Preprocessor allows inserting text from a specifed file
335. etween two characters that has a Vv side of it and a w on the other side of it in either order counting the imaginary characters off the beginning and end of the string as matching a Vw Vb 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 or more greedy similar to 0 one or more greedy similar to 1 Zero or one greedy similar to 0 1 n exactly n times greedy n atleast n times greedy n m atleast n but not more than m times greedy Zero or more non greedy similar to 0 2 or more non greedy similar to 1 Zero or one non greedy similar to 0 1 nj exactly n times non greedy n atleast 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 match es 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
336. f Write Sector 258 Cf Fat Init occ eee n 259 Cf Fat QuickFormat esasa eee 259 Cf Fat aa SUR 260 Cf Fat 261 Cf Fat Read eec eed dete 261 Cf Fat 262 Cf Fat Append uuu zer te EE A DR ES e RUE 262 Cf Fat ed DI epe 262 CT Fat Write ia Se n Eu Res PEG eRe 263 Cf Fat Set File 264 Cf Fat Get File 265 Cf Fat Get _5 266 Cf Fat Get 267 Library ae IRE NER EE 269 HW Connection 274 EEPROM Library 275 Library Routines 275 EEPROM 275 EEPROM Wile sea RR ERE i RE ER 276 Library 277 Flash Memory Library 278 Library Ro tlnes 2n e044 Om edad pada
337. ffer 512 y ne Writes string to USART void I Write Str char ostr unsigned short i MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 269 CHAPTER 6 Libraries mikroC PRO for AVR 0 while ah ostr i UART1 Write ostr i UART1 Write 0 0 void M Create New File filename 7 A Creates new file and writes some data to it Cf Fat Assign amp filename 0x80 Will not find file and then create file Cf Fat Rewrite To clear file and start with new data for loop 1 loop lt 99 1 We want 5 files on the MMC card file contents 0 loop 10 48 file contents 1 loop 10 48 Cf Fat Write file contents 38 write data to the assigned file UARTl Write gg eee Creates many new files and writes data to them void M Create Multiple Files for loop2 loop2 lt Z 1 244 UART1 Write loop2 filename 7 loop2 set filename Cf Fat Assign amp filename 0xA0 find existing file or cre ate a new one Cf Fat Rewrite To clear file and start with new data for loop 1 loop lt 44 1 44 file contents 0 loop 10 48 file contents 1 loop 10 48 Cf Fat Write file contents 38 write data to the assigned file void M Open File Rewrite Opens an existing file and rewrites it 270 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAP
338. from the project group Add file to the active project Remove selected file from the project Build the active project 2 S 6 Ea Ca GR 8 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 48 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment PROJECT SETTINGS WINDOW Following options are available in the Project Settings Window Device select the appropriate device from the device drop down list Oscillator enter the oscillator frequency value Value 10 000000 MHz MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 49 CHAPTER 2 Environment mikroC PRO for AVR LIBRARY MANAGER Library Manager enables simple handling C Library Manager es libraries being used in a project Library Manag er window lists all libraries extencion mcl which are instantly stored in the compiler Uses folder The desirable library is added to the proj ect by selecting check box next to the library name J ADC V Button 7 CAN SPI Compact Flash FAT16 Compact Flash In order to have all library functions accessible D simply press the button Check Al
339. g 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 0x200 Function will start at address 0x200 nop It is possible to use org directive with functions that are defined externally such as library functions Simply add org directive to function declaration void UART1 Write char data org 0x200 Note Directive org can be applied to any routin except for interrupt Note See also funcall pragma 104 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroC PRO for AVR Specifics Directive orgal If the user wants to place its routines constants etc above a specified address in ROM pragma orgall directive should be used pragma orgall 0x200 This doesn t apply to IVT Handler table and Goto table Directive funcorg You can use the pragma orgall directive to specify the starting address of a rou tine in ROM using routine name only pragma funcorg func name starting address 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 11 directive to ins
340. g 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 122 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference char name mikro foo just one token here Line Splicing with Backslash 1 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 mikroC PRO V Compiler parses into mikroC PRO Compiler Refer to String Constants for more information COMMENTS Comments are pieces of a text used to annotate a program and technically are another 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 PRO for AVR You should also follow the guidelines on the use of whitespace and delimiters in comments discussed later in this topic to avoid other portability problems C comments C comment is any sequence of characters placed after the symbol pair The com ment terminates at the first occurance of the pair following the initial The entire sequence including four comme
341. g pin as output Port Expander must be initialized See Expander Init Example Set Port Expander s PORTB to be input Expander Set DirectionPortB 0 0xFF MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 361 CHAPTER 6 Libraries mikroC PRO for AVR Expander_Set_DirectionPortAB void Expander Set DirectionPortAB char ModuleAddress unsigned int Direction Nothing The function sets Port Expander s PortA and PortB direction Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Direction data to be written to direction 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 Requires Port Expander must be initialized See Expander Init Exmpe Set Port Expander s PORTA to be output and PORTB to be input Description Expander Set DirectionPortAB 0 0x00FF Expander Set PullUpsPortA Prototype Expander Set PullUpsPortA char ModuleAddress char Data Nothing The function sets Port Expander s PortA pull up down resistors Parameters Description ModuleAddress Port Expander hardware address see schem
342. ge Reference mikroC PRO for AVR Sz if val 0 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 is goto label identifier This will transfer control to the location of a local label specified by label identi fier The 1abel identifier has to be a name of the label within the same func tion in which the goto statement is The goto line can come before or after the label goto Is used to break out from any level of nested control structures but it cannot be used to jump into block while skipping that block s initializations for example jump ing into loop s body etc The use of goto statement is generally discouraged as practically every algorithm can be realized without it resulting in legible structured programs One possible application of the goto statement is breaking out from deeply nested control structures Dor Vee d for 122 1 if disaster goto Error Error error handling code 216 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference RETURN STATEMENT The return statement is used to exit from the current function back to the calling routine optionally returning a value The syntax is return expression This will evaluate expression and r
343. gnal pin CD EN Direction Direction of the Enable signal pin LCD RST Direction Direction of the Reset signal pin LCD DataPort Direction Direction of the Data port must be defined before using this function pinout settings char GLCD DataPort at PORTC char GLCD DataPort Direction at DDRC sbit GLCD CS1 at PORTD B2 sbit GLCD CS2 at PORTD B3 sbit GLCD RS at PORTD B4 sbit GLCD RW at PORTD B5 sbit GLCD RST at PORTD B6 sbit at PORTD B7 sbit GLCD CS1 Direction at DDRD B2 sbit GLCD CS2 Direction at DDRD B3 sbit GLCD RS Direction at DDRD B4 sbit GLCD RW Direction at DDRD B5 sbit iCD Direction at DDRD B6 sbit GLCD RST Direction at DDRD B7 Glcd O MM 284 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Glcd_Set_Side Prototype Glcd Set Side unsigned short x pos Selects Glcd side Refer to the Glcd datasheet for detailed explaination Parameters x pos position on x axis Valid values 0 127 Description The parameter x 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
344. guage Reference FILE INCLUSION The preprocessor directive include pulls in header files extension h into the source code Do not rely on preprocessor to include source files extension see Add Remove Files from Project for more information The syntax of the include directive has two formats include header name gt include header name The preprocessor removes the include line and replaces it with the entire text of a header 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 is used with the lt header name gt version the search is made successively in each of the following locations in this particular order 1 the mikroC PRO for AVR installation folder include folder 2 user s custom search paths The header name version specifies a user supplied include file the mikroC PRO for AVR 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 PRO for AVR 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 include C WVmy
345. har FLASH Read Word unsigned int address Prototype for MCUs with Flash memory larger than 64kb char FLASH Read Word unsigned long address Returns Returns data word from Flash memory Description Reads data from the specified address in Flash memory for MCUs with Flash memory larger than 64kb unsigned long tmp tmp Flash Read 0x0D00 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 279 CHAPTER 6 Libraries mikroC PRO for AVR FLASH_Read_Words for MCUs with 64kb of Flash memory or less void FLASH Read wWrds unsigned int address char buffer unsigned NoWords Prototype for MCUs with Flash memory larger than 64kb void FLASH Read 2 long address char buffer unsigned NoWords Description Reads number of data words defined by NoWords parameter from the specified address in Flash memory to varibale pointed by buffer for MCUs with Flash memory larger than 64kb const long F_ADDRESS 0x200 unsigned int dat buffi 32 FLASH Read Words ADDRESS dat buff 32 Library Example The example demonstrates simple write to the flash memory for AVR then reads the data and displays it on PORTB and PORTD const long F ADDRESS 0x200 const unsigned int data 32 constant table 0x0000 0x0001 0x0002 0x0003 0x0004 0x0005 0x0006 0x0007 0x0008 0x0009 0x000A 0x000B 0x000C 0x000D 0x000E 0x000F 0x0000 0x0100 0x0200 0x0300 0x0400 0x0500 0x0600 0x070
346. he following manner Description data 0 2 message content number of message bytes received 1 3 is set to 255 when message is received is set to 255 if error has occurred address of the Slave which sent the message The function automatically adjusts 4 and 51 upon every received message These flags need to be cleared by software MCU must be initialized as a Master for RS 485 communication See q RS485Master Init char msg 8 RS485Master Receive msg 392 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries RS485Master_Send Prototype Description void RS485Master Send char data_buffer char datalen char Slave address Nothing 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 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 char msg 8 send 3 bytes of data to Slave with address 0x12 RS485Master Send msg 3 0x12 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 393 CHAPTER 6 Libraries mikroC PRO for AVR RS485Slave_Init Prototype
347. hh Eua Vida nee aba bad 128 rec TET 128 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD IX Table of Contents mikroC PRO for AVR Floating Point Constants 129 Character Constants 130 Escape Sequences 130 Disambiguation 131 String Constants silicon RR ER te oad bead Goya Td lxi 132 Line Continuation with Backslash 132 Enumeration Constants 133 Constant Expressions 135 Keywotds us I pea SR eA eu dE TA ee 136 Identifiers 137 Case Sensitivity s Re pe bee deep d ati 137 Uniqueness and Scope 137 Identifier Examples 137 P rictuators ett eed Maleate med ein 138 Brackels a aisea raa Dre 138 Parentheses a aa RA IRR ER p 138 Braces a RR a Waals RR 139 Ree etur et eee e eai 139 SEMICOION aii eee a S D Va ee 139 em MUERTE IE 140 Asterisk Pointer Declaration 140 Equal SIgn zoe Ee xen Racks ee
348. ic duration variable init b only upon first call to f static int b 1 checkpoint att btt void main At checkpoint we will have f asl bsl after first call a 1 b 2 after second call 1 b 3 after third call etc 148 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference TYPES The mikroC PRO for AVR is a strictly typed language which means that every object function and expression must have a strictly defined type known in the time of compilation Note that the mikroC PRO for AVR 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 PRO for AVR supports many standard predefined and user defined data types including signed and unsigned integers in various sizes floating point numbers with various precisions arrays structures and unions In addition point ers to most of these objects can be established and manipulated in memory The type determines how much memory is allocated to an object and how the 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 im
349. icture preview 128x64 pix bw Load BMP Picture CreteCODE we GLCD Size controller GLCD Picture name truck bmp GLCD Model 80108 28x64 L const Enck oat 2 arra byte CODE be a 0 2 8 8 5 8 8 12 12 12 12 12 10 19 18 10 18 18 9 195 9 9 9 137 137 137 137 137 137 132 132 437 137 437 437 137 9 9 9 9 9 9 9 95 9 9 9 13 253 13 195 6 252 0 B 8 8 6 B 2 0 1 27012005 System status Win like OS MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 65 CHAPTER 2 Environment mikroC PRO for AVR LCD Custom Character mikroC PRO for AVR includes the LCD Custom Character Output is mikroC PRO for AVR compatible code You can launch it from the drop down menu Tools LCD Custom Character a a Save Load Fill all Clear Invert CGRAM address Char 0 I 0 Char data row GENERATE 66 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR CHAPTER 2 Environment Options menu consists of three tabs Code Editor Tools and Output settings The Code Editor is advanced text editor fashioned to satisfy needs of professionals The mikroC PRO for AVR includes the Tools tab which enables the use of shortcuts to external programs like Calculator or Notepad You can set up to
350. id printhex unsigned char i unsigned char hi lo hi i amp OxF0 High nibble hi hi gt gt 4 ha pi 10n if hi gt 9 hi hi 7 lo 4 OxOF 0 Low nibble if l10 9 loslotT7 UART1 Write hi UART1 Write lo char Spi Rd Ptr char SPI1 Read void main unsigned int i PORTC 0 ifdef RS232 debug UART1 Init 19200 fendif Delay ms 10 336 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries ifdef RS232 debug UART1 Write Text PIC Started If PIC present report UART1 Write 13 UART1 Write 10 endif Before all we must initialize a MMC card 5 1 Init Advanced SPI MASTER SPI FCY DIV2 SPI CLK LO LEAD ING Spi Rd Ptr SPI1 Read i Mme Init ifdef RS232 debug if i 0 UART1 Write Text MMC Init OK If MMC present report UART1 Write 13 UART1 Write 10 LE i UART1 Write Text MMC Init error If error report UART1 Write 13 UART1 Write 10 fendif for i 0 i 511 i dData i E Fill MMC buffer with same characters i Mmc Write Sector 55 dData ifdef RS232 debug if i 0 UART1 Write Text Write OK else if there are errors UART1 Write Text Write Error UART1 Write 13 UART1 Write 10 fendif Reading of CID and CSD register on MMC card ifdef RS232 debug i Mmc Rea
351. idth precision 4 X hg conversion type 568 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Description Each field in the format specification can be a single character or a number which specifies a particular format option The conversion type field is where a single character specifies that the argument is interpreted as a character string number or pointer as shown in the following table os p eee n Unsigned hexadecimal number using 0123456789abcdef Unsigned hexadecimal number using 0123456789ABCEDF EC Floating point number using the for mat dddd dddd Floating point number using the for Floating point number using the for Floating point number using either e or f format whichever is more compact for the specified value and precision int is converted to unsigned char and the resulting character is written String with a terminating null character Pointer value the X format is used A is written No argument is con lt gt verted complete conversion specification shall be The flags field is where a single character is used to justify the output and to print signs and blanks decimal points and octal and hexadecimal prefixes as shown in the following table MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 569 CHAPTE
352. in the brackets deter mines a number of elements in array If an expression is given in an array declara tor it must evaluate to a positive constant integer The value is a number of ele ments in an array Each of the elements of an array is indexed from 0 to the number of elements minus one If a number of elements is n elements of array can be approached as variables array name 0 array name n 1 of type Here are a few examples of array declaration define MAX 50 nite vector one 10 declares an array of 10 integers float vector two MAX declares an array of 50 floats mn float vector three MAX 20 declares an array of 30 floats y MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 155 CHAPTER 5 Language Reference mikroC PRO for AVR Array Initialization An array can be initialized in declaration by assigning it a comma delimited sequence of values within braces When initializing an array in declaration you can omit the number of elements it will be automatically determined according to the number of elements assigned For example Declare an array which holds number of days in each month int days 12 31 28 31 30 31 30 31 31 30 31 30 31 This declaration is identical to the previous one int days 31 28 31 30 31 30 31 31 30 31 30 31 If you specify both the length and starting values the number of starting values must not exceed the specified length
353. incide 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 144 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference void f int i int 7 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 j 0 1 i and double j are visible int j 3 in scope but hidden double j out of scope j t 1 int j visible and 4 i and j are both out of scope MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 145 CHAPTER 5 Language Reference mikroC PRO for AVR NAME SPACES Name space is a scope within which an identifier must be unique The mikroC PRO for AVR 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 defi
354. inished the data can be re written into a normal file and formatted in the most suitable way Parameters sectors cnt humber of consecutive sectors that user wants the swap file to have filename name of the file that should be assigned for file operations File name should be in DOS 8 3 file name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does no have to take care of that The file name and extension are case insensitive The library will convert them to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between file name and extension i e MIKROELETXT gt MIKROELE TXT In this case last 3 charac ters of the string are considered to be file extension file attr creation and attributs flags Each bit corresponds to appropriate file attribut 334 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Bt Was Beson oom Reim _ s wem Dee mermar use ony never ound on aK Note Long File Names LFN are not supported MMC SD card and MMC library must be initialized for file operations See Requires
355. init Options Direction Case sensitivity Forward Whole words only Search from caret Backward Selected text only Regular expression OK Cancel Dialog box for searching for a text string in file and replacing it with another text string 4 Replace Text Search for mikroElektronika Replace with mikroE Direction v Case sensitivity 9 Forward enn Whole words only Backward Search from caret Selected text only Regular expression Cancel MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 17 CHAPTER 2 Environment mikroC PRO for AVR Find In Files Dialog box for searching for a text string in current file all opened files or in files on a disk The string to search for is specified in the Text to find field If Search in directories option is selected The files to search are specified in the Files mask and Path fields Text to find Options a Case sensitive Search directory options C Program filesi Go To Line Dialog box that allows the user to specify the line number at which the cursor should be positioned Go To Line Nuber 18 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment Regular expressions By checking this box you will be able to advance your search through Regular expressions E NCH NN Related topics
356. ints like this Name Address The Name is preceded by two tabs The Address is preceded by one tab The line is followed by two new lines The provides interior double quotes The escape character sequence is translated into by the compiler Adjacent string literals separated only by whitespace are concatenated during the parsing phase For example is T example is equivalent to This is just an example Line Continuation with Backslash You can also use the backslash X 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 PRO for AVR Language Reference ENUMERATION CONSTANTS Enumeration constants are identifiers defined in enum 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 in any expression where integer constants are valid For example enum weekdays SUN 0 MON TUE WED THU FRI SAT The identifiers enumerators used must be unique within the scope of the enum declaration Negative initializers are allowed See Enumerations for details about enum declarations MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 133 CHAPTER 5 Language Reference mikroC PRO for AVR Pointer
357. ion PWM Phase Correct TOP BOTTOM 10 bit Example lets set duty ratio to PWM16bit Change Duty 300 _TIMER1 386 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries PWM 16bit_Start Prototype PWMi6bit Start unsigned int timer Description Starts PWM 16bit module with alredy preset values wave mode prescaler P inverted and duty given the PWMY16bit Init MCU must CMO module to use this library PWM16bit Init must be called Requires before using this routine otherwise it will have no effect as the PWM module is not initialised PWMl6bit Start TIMI Starts the PWM 16bit module on Timer Counterl or PWMl6bit Start Starts the PWM 16bit module on Timer Counter3 PWM 16bit_Stop Ne Re MCU must have CMO module to use this library Like in PWM16bit Start before Requires PWM 16bit_Init must be called before using this routine otherwise it will have no effect as the PWM module is not running PWMl6bit Stop TIMI Stops the PWM 16bit module on Timer Counterl or PWM16bit Stop Stops the PWM 16bit module on Timer Counter3 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 387 CHAPTER 6 Libraries mikroC PRO for AVR Library Example The example changes PWM duty ratio continually by pressing buttons on PORC 0 3 If LE
358. ion The functions CANSPIInitialize CANSPISetBaudRate CANSPISetMask and CANSPISetFilter expect one of these or a bitwise combina tion as their argument const char CANSPI CONFIG DEFAULT OxFF 11111111 CANSPI CONFIG PHSEG2 PRG BIT Ox01 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 244 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries CANSPI CONFIG DBL BUFFER BIT 0x10 CANSPI CONFIG DBL BUFFER ON OxFF XXX1XXXX CANSPI CONFIG DBL BUFFER OFF OxEF XXXOXXXX CANSPI CONFIG MSG BITS 0x60 CANSPI CONFIG ALL MSG OxFF XllXXXXX CANSPI CONFIG VALID XTD MSG OxDF Xl0XXXXX CANSPI CONFIG VALID STD MSG OxBF X01XXXXX CANSPI CONFIG ALL VALID MSG Ox9F X00XXXXX You may use bitwise AND amp to form config byte out of these values For example
359. ion of SPI T6963C Graphic Lcd Library routines is based on Port Expander Library routines Prior to calling any of this library routines Spi Rd Ptr needs to be initialized with the appropriate SPI Read routine External dependencies are the same as Port Expander Library external dependencies MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 483 CHAPTER 6 Libraries mikroC PRO for AVR Library Routines SPI T6963C Config SPI T6963C WriteData SPI T6963C WriteCommand SPI T6963C SetPtr SPI T6963C WaitReady SPI T6963C Fill SPI T6963C Dot SPI T6963C Write Char SPI T6963C Write Text SPI T6963C Line SPI T6963C Rectangle SPI T6963C Box SPI T6963C Circle SPI T6963C Image SPI T6963C Sprite SPI T6963C Set Cursor Note The following low level library routines are implemented as macros These macros be found in the ser T6963c 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 T6963C SetTxtPanel SPI_T6963C_Panel Fill SPI T6963C GrFill SPI T6963C TxtFill SPI T6963C Cursor Height SPI T6963C Graphics SPI T6963C Text SPI T6963C Cursor SPI T6963C Cursor Blink 484 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI_T6963
360. ip Select SoftSpi C LK at PORI 0 7 at PINB B6 Note TB BS Direction at DDRB B0 LK Direction at DDRB B7 SoftSpi SDI Direction at DDRB B6 SoftSpi SDO Direction at DDRB B5 End Software SPI module Soft SPI Init Init Soft SPI Input signal connections MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 411 CHAPTER 6 Libraries mikroC PRO for AVR Soft SPI Read Prototype unsigned short Soft SPI Read char sdata Returns Byte received via the SPI bus This routine performs 3 operations simultaneously It provides clock for the Soft ware SPI bus reads a byte and sends a byte Deseripuon Parameters sdata data to be sent Soft SPI must be initialized before using this function See Soft SPI Init routine unsigned short data read char data send Read a byte and assign it to data read variable data send byte will be sent via SPI during the Read opera tion data read Soft SPI Read data send Soft SPI Write This routine sends one byte via the Software SPI bus Description Parameters sdata data to be sent Soft SPI must be initialized before using this function See Soft SPI Init routine Write a byte to the Soft SPI bus Soft SPI Write 0xAA 412 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Library Example CHAPTER 6 Libraries This code demonst
361. it Direction of the sbit GLCD RS Direction D RS Direction Register select pin at D B4 t extern sfr sbit Direction of the sbit Direction GLCD RST Direction Reset pin at D 282 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Library Routines Basic routines Glcd Init Glcd Set Side Glcd Set X Glcd Set Page Read Data Glcd Write Data Advanced routines Glcd Fill Dot Glcd_Line Glcd V Line Glcd H Line Glcd Rectangle Glcd Box Glcd Circle Glcd Set Font Write Char Glcd Write Text Glcd Image MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 283 CHAPTER 6 Libraries mikroC PRO for AVR Glcd Init Description Initializes the module Each of the control lines is both port and pin config P urable while data lines must be on a single port pins lt 0 7 gt Global variables LCD CS1 Chip select 1 signal pin LCD CS2 Chip select 2 signal pin LCD RS Register select signal pin LCD RW Read Write Signal pin LCD EN Enable signal pin LCD RST Reset signal pin LCD DataPort Data port Requires LCD CS1 Direction Direction of the Chip select 1 pin LCD CS2 Direction Direction of the Chip select 2 pin LCD RS Direction Direction of the Register select signal pin LCD RW Direction Direction of the Read Write si
362. it SPI Ethernet Rst at PORTB B4 sfr sbit SPI Ethernet CS at PORTB B5 sfr sbit SPI Ethernet Rst Direction at DDRB B4 sfr sbit SPI Ethernet CS Direction at DDRB B5 end ethernet NIC definitions EEKE KK Ck kk kk kk Ck kk kk OK kk k k kk kk Ck CK k k k Kok k k ko ke kc k k kk ko ok ke ke ke e e ek ROM constant strings m const code unsigned char httpHeader HTTP 1 1 200 OKnContent type HTTP header const code unsigned char httpMimeTypeHTML 1 text htmlnn HTML MIME type const code unsigned char httpMimeTypeScript text plainnn TEXT MIME type 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 content 3 url http 192 168 20 60 gt lt HTML gt lt HEAD gt lt HEAD gt lt BODY gt lt h1 gt AVR ENC28J60 Mini Web lt 1 gt lt a href gt Reload lt a gt lt script src s gt lt script gt table tr td table border 1 style font size 20px terminal gt tr th colspan 2 gt PINC lt th gt lt tr gt script yar strpi str for 1 0 1 lt 8 1 strt t lt tr gt lt td bgcolor pink gt BUTTON it lt td g
363. iterals can be passed as a text Description Parameters text text to be written Requires Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routines Write text Here at current cursor position SPI Led8 Out Cp Here 478 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI Lcd8 Chr void SPI Lcd8 Chr unsigned short row unsigned short column char out char Prints character on Lcd at specified position Both variables and literals can be passed as character Prototype Parameters Description row writing position row number column writing position column number out char Character to be written Requires Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routines STRE Write character i at row 2 column 3 SPI Lcd8 Chr 2 3 a SPI Lcd8 Chr Cp Prototype SPI Lcd8 Chr CP char out char Prints character on Lcd at current cursor position Both variables and literals can be passed as character Description Parameters out char character to be written Lcd needs to be initialized for SPI communication see SPI Lcd8 Config routines Print at current cursor position Write character e at current cursor position SPI Lcd8 Chr Cp e MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 479 CHAPTER 6 Libraries
364. ith 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 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 main res func limit ch function call Since the program has the function prototype for func it converts limit and ch to long using the standard rules of assignment before it places them on the stack for the call to func Without the function prototype 1imit and ch would be placed on the stack as integer and a character respectively in that case the stack passed to unc will not match size or content that func expects which can cause problems MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 191 CHAPTER 5 Language Reference mikroC PRO for AVR 192 Ellipsis Operator The ellipsis consists of three successive periods with no whitespace inter vening 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 void tunc int n char ch This declaration indicates that func will be defined in such a way that calls must have at least two arg
365. itialize 1 3 3 3 1 Can Init Flags initialize external CANSPI module 238 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries CANSPISetBaudRate void CANSPISetBaudRate char SJW char BRP char PHSEG1 char PHSEG2 char PROPSEG char CAN CONFIG FLAGS Nothing 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 CAN CONFIG FLAGS value Refer to datasheet for details Parameters Description SJW 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 is formed from predefined constants see CANSPI constants The CANSPI module must be in Config mode otherwise the function will be ignored See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page set required baud rate and sampling rules char can config flags CANSPISetOperationMode CANSPI MODE CONFIG OxFF Z set CONFIGURATION
366. ition To view all breakpoints select Run gt View Breakpoints from the drop down menu Double clicking an item in the Breakpoints Window List locates the breakpoint Execute all instructions between the current Run to cursor s F4 instruction and cursor position Execute the current C single or multi cycle ten Gees instruction then halt If the instruction is a rou F7 tine call enter the routine and halt at the first instruction following the call Execute the current C single or multi cycle instruction then halt E Execute all remaining instructions in the current routine return and then halt Related topics Run Menu Debug Toolbar Toggle Breakpoints 220321223 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 95 CHAPTER 2 Environment mikroC PRO for AVR CREATING NEW LIBRARY mikroC PRO for AVR allows you to create your own libraries In order to create a library in mikroC PRO for AVR 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 ProgramFiles Mikroelektronika mikroC PRO for AVR Uses Lib Example 3 Write a code for your library and save it 4 Add Lib Example file in some project see Project Manager Recompile the project 5 Compiled file Lib Example mcl should appear in mikroC PRO for AVR Uses folder 6 Open the definition file for the MCU that you want t
367. ively hide and display sec tions of a source file In this way it is easier to manage large regions of code within one window while still viewing only those subsections of the code that are relevant during a particular editing session While typing the code folding symbols and appear automatically Use the folding symbols to hide unhide the code subsections main t PORTA 0 PORTB 0 Lcd Init LCD Out 1 1 txt 0 LCD Out 2 1 txt 1 delay 1000 Lcd 1 LCD Out i1 1 txt 1 LCD Out 2 4 txt 2 delay ms 500 void If you place a mouse cursor over the tooltip box the collapsed text will be shown in a tooltip style box void main he void main n PORTS 0 PORTB 0 Lcd Init LCD Out 1 1 txt 0 LCD Out 2 1 txt 1 delay ms 1000 Lcd Cmd 1 LCD Out 1 1 txt 1 LCD Out 2 4 txt 2 delay ms 500 42 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment Parameter Assistant The Parameter Assistant will be automatically invoked when you open parenthesis or press Shift Ctrl Space If the name of a valid function precedes the parenthe sis then the expected parameters will be displayed in a floating panel As you type the actual parameter the next expected parameter will become bold channel char ADC Rea Code Templates Auto Complete You can insert the C
368. kroElektronika void main Man Send Init Initialize transmitter while 1 Endless loop Man Send 0x0B Send start byte Delay ms 100 Wait for a while 320 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries character sl 0 Take first char from string index 0 Initialize index variable while character String ends with zero Man Send character Send character Delay ms 90 Wait for a while index Increment index variable character sl index Take next char from string Man 0 0 Delay ms 1000 Send end byte Connection Example Transmitter RF module Antenna NV ae OSCILLATOR vcc 9LVOANLV A RT4 m GND Simple Transmitter connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 321 CHAPTER 6 Libraries mikroC PRO for AVR Receiver RF module Antenna VCCo OSCILLATOR EH bY gt GND o RR4 GND Simple Receiver connection 322 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR CHAPTER 6 MULTI MEDIA CARD LIBRARY The Multi Media Card MMC is a flash memory card standard MMC cards are cur rently available in sizes up to and including 1 GB and
369. l parameter is declared as a pointer The pointed object can be accessed by using the indirection operator For example Soft Uart Read takes the pointer to error variable so it can change the value of an actual argument Soft Uart Read amp error The following code would be wrong you would pass the value of error variable to the function Soft Uart Read error 190 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference Argument Conversions If a function prototype has not been previously declared the mikroC PRO for AVR converts integral arguments to a function call according to the integral widening expansion rules described in Standard Conversions If a function prototype is in scope the mikroC PRO for AVR converts the passed argument to the type of the declared parameter according to the same conversion rules as in assignment state ments 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 accept able to a function prototype Note If the function prototype does not match the actual function definition the mikroC PRO for AVR will detect this if and only if that definition is in the same com pilation unit as the prototype If you create a library of routines w
370. l t and all v GLCD libraries will be selected In case none library is GLCD Fonts Keypad 4x4 v LCD and all libraries will be cleared from the LCD Constants 7 MMC 7 MMC 16 Only the selected libraries will be linked 7 One Wire T Port Expander 7 ps2 7 PwM 7 5485 7 Software I2C V Software SPI Software UART Sound spr E SPI GLCD SPI LCD 7 SPILCD8 SPI T6963 V Sprintf Sprinti Sprintl E Stdlib C String T6963 Time C Trigonometry 7 TWI V USART needed in a project press the button Clear All project 50 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment Icon Description p Refresh Library by scanning files in Uses folder Useful when new libraries are added by copying files to Uses folder Rebuild all available libraries Useful when library sources are avail able and need refreshing ale Include all available libraries in current project u No libraries from the list will be included in current project d Restore library to the state just before last project saving Related topics mikroC PRO for AVR Libraries Creating New Library MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 51 CHAPTER 2 Environment mikroC PRO for AVR ERROR
371. lays ROM memory usage in form of histogram MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 55 CHAPTER 2 Environment mikroC PRO for AVR ROM Memory Allocation Displays ROM memory allocation 0 0000 0 0 942 n 4 RAM 0 0004 0 0 9400 E RxData 0 0008 0 0 9400 E Data Ox000C 0 0 9400 SFR 0 0010 0 0 9400 GPR 0 0014 0x0C9400 4 ROM 00016 05069400 ROM Allocation 0x0020 0 0 9400 4 Procedures 0 0024 0x0C9400 Size 0 0028 0 0 9400 Locations Ox002C 0 0 9400 HTML 0x0030 0 0 9400 0 0034 0 0 9400 0 0038 0 0 9400 0 003 0 0 9400 0 0040 0 0 9400 0 0044 OxOC9400 0 0048 0 0 9400 0 004 0 0 9400 0 0050 0 0 9400 0 15 2 0 22 5 OxlSF4 0 2 0 15 6 0 00 0 Oxl5F8 0 0 495 OxlSFA 1 7 OxlSFC 0 1 95 L Procedures Windows Provides overview procedures locations and sizes 56 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment Procedures Size Window Displays size of each procedure Procedures Locations Window Displays how functions are distributed in microcontroller s memory MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 57 CHAPTER 2 Environment mikroC PRO for AVR HTML Window Display statistics in default web browser You can generate statistics in HTML format too It is suitable for prin
372. le from Project Icon x MIKROELEKTRONIKA SOFTWARE HARDWARE SOLUTIONS FOR EMBEDDED WORLD 81 CHAPTER 2 Environment mikroC PRO for AVR Project Level Defines Project Level Defines 1d files can also be added to project Project level define files enable you to have defines that are visible in all source files in the project A file must contain one definition per line in the following form lt symbol gt lt value gt symbol a b gt lt value gt Define a macro named symbol To specify a value use lt value gt If lt value gt is omitted 1 is assumed Do not enter white space characters immediately before the f a white space character is entered immediately after the the macro is defined as zero token This option can be specified repeatedly Each appearance of symbol will be replaced by the value before compilation There are two predefined project level defines see predefined project level defines 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 82 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment 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 mcpav along with oth
373. le signal line F sfr char CF Data Port at PORTD sfr char CF Data Port Direc tion at DDRD sbit CF R PINB B7 sbit CF WE PORTB B6 sbit CF C PINB B4 Dl at sbit CF at PORTB B3 sbit CF A2 at PORTB B2 sbit CF A1 at PORTB B1 sbit CF at PORTB BO sbit CF RDY direction at DDRB B7 CF WE direc at DDRB B6 CF ORB dirrec at DDRB B5 sbit CF CD1 direction at DDRB B4 sbit 1 direction at DDRB B3 sbit CF A2 direc tion at DDRB B2 252 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries extern sfr sbit Direction of the Address sbit CF A1 direc CF Al direction 1 pin tion at DDRB Bl1 extern sfr sbit Direction of the Address sbit CF A0 direc CF A0 direction 0 pin tion at DDRB B0 Library Routines Cf Init Cf Detect Cf Enable Cf Disable Cf Read Init Cf Read Byte Cf Write Init Cf Write Byte Cf Read Sector Cf Write Sector Routines for file handling Cf Fat Init Cf Fat QuickFormat Cf Fat Assign Cf Fat Reset Cf Fat Read Cf Fat Rewrite Cf Fat Append Cf Fat Delete Cf Fat Write Cf Fat Set File Date Cf Fat Get File Date Cf Fat Get File Size Cf Fat Get Swap File The following routine is for the internal use by compiler only Cf Issue ID Command MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR
374. library functions for testing and map ping characters Note Not all of the standard functions have been included Note The functions have been mostly implemented according to the ANSI C standard but cer tain functions have been modified in order to facilitate AVR programming 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 Description Function returns 1 if the character is alphanumeric A Z a z 0 9 otherwise returns zero isalpha Prototype unsigned short isalpha char character Description Function returns 1 if the character is alphabetic A Z a z otherwise returns zero iscntrl Prototype unsigned short iscntrl char character Description Function returns 1 if the character is a control or delete character decimal 0 31 and 127 otherwise returns zero 542 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries isdigit Prototype unsigned short isdigit char character Function returns 1 if the character is a digit 0 9 otherwise returns zero isgraph Prototype unsigned short isgraph char character n Function returns 1 if the character is a printable excluding the space decimal D
375. llocated 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 static duration by using the explicit static Or extern storage class specifiers In the mikroC PRO for AVR 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 duration and local scope see the example below Local Duration Local duration objects are also known as automatic objects They are created on the stack or in a register when an enclosing block or a function is entered They are deallocated when the program exits that block or function Local duration objects must be explicitly initialized otherwise their contents are unpredictable The storage class specifier auto can be used when declaring local duration vari ables but it is usually redundant because auto is default for variables declared within a block An object with local duration also has local scope because it does not exist outside of its enclosing block On the other hand a local scope object can have static dura tion For example MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 147 CHAPTER 5 Language Reference mikroC PRO for AVR local duration variable init a upon every call to f int a 1 stat
376. locates the first occurrence of the string s2 in the string s1 excluding the terminating null character The function returns pointer to first occurrence of s2 in s1 if no string was found function returns o If s2 is a null string the function returns 0 char strcspn char sl char s2 Function computes the length of the maximum initial segment of the string point ed to by s1 that consists entirely of characters that are not in the string pointed The function returns the length of the initial segment char strpbrk char sl char s2 Function searches s1 for the first occurrence of any character from the string s2 The terminating null character is not included in the search The function returns pointer to the matching character in s1 If s1 contains no characters from s2 the function returns 0 char strrchr char ptr unsigned int chr Function searches the string ptr for the last occurrence of character chr The null character terminating ptr is not included the search The function returns pointer to the last chr found in ptr if no matching character was found function returns 0 558 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries BUTTON LIBRARY The Button library contains miscellaneous routines useful for a project development External dependecies of Button Library The following variable must be defined in all E D
377. lock MHz Get Fosc kHz Returns Lowest 8 bits byte of number bits 7 0 Function returns the lowest byte of number Function does not interpret bit pat terns of number it merely returns 8 bits as found in register Description This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Arguments must be variable of scalar type i e Arithmetic Types and Pointers d Ox1AC30F4 tmp Lo d Equals OxF4 106 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroC PRO for AVR Specifics Hi Returns Returns next to the lowest byte of number bits 8 15 Function returns next to the lowest byte of number Function does not interpret bit patterns of number it merely returns 8 bits as found in register Description This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Arguments must be variable of scalar type i e Arithmetic Types and Pointers i Equals 0x30 Higher Returns Returns next to the highest byte of number bits 16 23 Function returns next to the highest byte of number Function does not interpret bit patterns of number it merely returns 8 bits as found in register Description This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call li
378. loss of infor mation char some byte 0x0A Write a byte via Soft Uart Soft UART Write some byte 418 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Soft_UART_Break Soft_UART_Read is blocking routine and it can block the program flow Call this routine from interrupt to unblock the program execution This mechanism is simi Description ae Note Interrupts should be disabled before using Software UART routines again see note at the top of this page char datal error counter 0 void Timer0Overflow_ ISR org 0x12 if counter gt 20 Soft UART Break counter 0 reset counter else increment counter void main TOIEO bit Timer0 overflow inter rupt enable TCCRO bit Start timer with 1024 prescaler SREG I 0 Interrupt disable Soft UART Init 9600 Soft UART Write 0x55 try Soft UART Read with blocking prevention mechanism SREG I bit 1 Interrupt enable datal Soft UART Read amp error SREG I bit 0 Interrupt disable MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 419 CHAPTER 6 Libraries mikroC PRO for AVR Library Example This example demonstrates simple data exchange via software UART If MCU is connected to the PC you can test the example from the mikroC PRO for AVR USART Terminal Tool Soft UA
379. m Compact Flash sector buffer Note Higher byte of the unsignea return value is cleared Reads one byte from Compact Flash sector buffer location currently pointed to Description by internal read pointers These pointers will be autoicremented upon reading The corresponding MCU ports must be appropriately initialized for CF card See Cf Init CF card must be initialized for reading operation See Cf Read Init Read a byte from compact flash char data data Cf Read Byte 256 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Cf_Write_Init Prototype void Cf Write Init unsigned long address unsigned short sectcnt Initializes CF card for writing Parameters Description address the first sector to be prepared for writing operation sectcnt number of sectors to be prepared for writing operation The corresponding MCU ports must be appropriately initialized for CF card See Requires Cf Init initialize compact flash for writing to sector 590 Write Inxt 590 1 Cf Write Byte Prototype void Cf Write Byte unsigned short data Writes a byte to Compact Flash sector buffer location currently pointed to by writ ing pointers These pointers will be autoicremented upon reading When sector buffer is full its contents will be transfered to appropriate flash memory sector Description Parameters
380. ment Although small this contoller has a capability of displaying and merging text and graphics and it manages all the interfacing signals to the displays Row and Col umn drivers For creating a custom set of GLCD images use GLCD Bitmap Editor Tool Note ChipEnable CE FontSelect FS and Reverse MD have to be set to appro priate levels by the user outside of the T6963c_Init function See the Library Exam ple code at the bottom of this page Note Some mikroElektronika s adapter boards have pinout different from T6369C datasheets Appropriate relations between these labels are given in the table below Adapter Board T6369C datasheet 506 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR CHAPTER 6 Libraries External dependencies of T6963C Graphic LCD Library The following variables must be defined in all projects using T6963C Graphic LCD library extern sfr T6963C data extern sfr extern sfr T6963C data tion extern sfr T6963C ctrl tion extern sfr T6963C ctrl extern sfr T6963C ctrlrd extern sfr T6963C ctrlcd extern sfr T6963C ctrl extern sfr T6963C ctrl on extern sfr T6963C ctrl on extern sfr T6963C ctrl on extern sfr T6963C ctrl ion MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD T6963C ctrlE char Port char Port Direc char Port Direc sbit wr Directi sbit rd Directi sbit
381. mikroC PRO for AVR HW Connection MCP23S17 Ne Do 15 epeo Gpa7 72 D1 2g H27 FS GPB1 GPA6 D2 39 H 26 MD GPB2 5 D3 44 25 RST GPB3 GPA4 D4 54 24 GPB4 GPA3 05 le 2 gt PBS 06 74 22 RW GPB6 GPA1 D7 84 H 21 RS GPB7 GPAO 94 H 20 vcco VDD INTA VCCo m vss INTB 23 OSCILLATOR a PB 1 1527 H4s PBo cs RESET 1 PB 7 124 H7 SCK A2 Js gt PB 5 134 EE si po PB 6H H 15 14 50 ao 3 Toshiba T6963C Graphic LCD 240x128 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 10K Contrast Adjustment SPI T6963C Glcd HW connection CHAPTER 6 Libraries 505 CHAPTER 6 Libraries mikroC PRO for AVR T6963C GRAPHIC LCD LIBRARY The mikroC PRO for AVR provides a library for working with GLCDs based on TOSHIBA T6963C controller The Toshiba T6963C is a very popular LCD controller for the use in small graphics modules It is capable of controlling displays with a res olution up to 240x128 Because of its low power and small outline it is most suitable for mobile applications such as PDAs MP3 players or mobile measurement equip
382. mikroC PRO for AVR SPI Lcd8 Cmd Sends command to Lcd Parameters Description 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 Lcd8 Config routines Clear Lcd display SPI Lcd8 Cmd Lcd CLEAR Available Lcd Commands Return cursor to home position returns a shifted display CD RETURN HOME to its original position Display data is unaffected Underline cursor on Shift display right without changing display data RAM 480 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Library Example This example demonstrates how to communicate Lcd in 8 bit mode via the SPI mod ule using serial to parallel convertor MCP23S17 char text mikroE Port Expander module connections sbit SPExpanderRST at PORTB BO sbit SPExpanderCS at PORTB B1 sbit SPExpanderRST Direction at DDRB B0 sbit SPExpanderCS Direction at DDRB B1 End Port Expander module connections void main If Port Expander Library uses SPI1 module SPIT Init Initialize SPI module used with PortExpander SPI Rd Ptr SPI1 Read Pass pointer to SPI Read function of used SPI module If Port Expander Library uses SPI2 module SPI2 Ini
383. mikroE two rows Initialize SPI module Pass pointer to SPI Read I2 module Initialize SPI module Pass pointer to SPI Read Initialize Lcd over SPI Clear display Turn cursor off Print text to Lcd Ist 1 Append Print text to Lcd 2nd For Led with more than For Led with more than 474 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries HW Connection 23517 1 28 GPBO GPA7 _K 24 27 GPB1 GPA6 RS 34 26 GPB2 GPA5 _ E 4 25 GPB3 GPA4 leva gt D4 GPB4 GPA3 05 6 23 m GPB5 GPA2 D6 7 22 r 5 6 GPA1 27 r GPA0 VCCo GND VCC 9 20 OSCILLATOR m O INTA um 10 19 c 111 MSS INTE 48 PBO fF J Ff H O ee gt PB 7 120 CS Res 17 sck A2 5 13 16 51 6 143 15 iso ao 4 VCC Contrast Adjustment 5K SPI Led HW connection MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 475 CHAPTER 6 Libraries mikroC PRO for AVR SPI LCD8 8 BIT INTERFACE LIBRARY The mikroC PRO for
384. mit ii iis must be variable of scalar type i e Arithmetic Types and Pointers 0x1AC30F4 22 Higher d Equals Highest Returns Returns the highest byte of number bits 24 31 Function returns the highest byte of number Function does not interpret bit pat terns of number it merely returns 8 bits as found in register Description This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit a must be variable of scalar type i e Arithmetic Types and Pointers Ox1AC30F4 n Highest d Equals 0x01 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 107 CHAPTER 3 Specifics mikroC PRO for AVR 108 Delay_us Prototype void Delay us const unsigned long time in us Creates a software delay in duration of time in us microseconds a constant Range of applicable constants depends on the oscillator frequency Description This is an inline routine code is generated in the place of the call so the call doesn t count against the nested call limit Example Delay us 1000 One millisecond pause Delay ms Prototype void Delay ms const unsigned long time in ms Creates a software delay in duration of time in ms milliseconds a constant Range of applicable constants depends on the oscillator frequency Description This is an inline routine code is generated in the place of the call so
385. mming practices If you are experienced in C programming you will probably want to consult mikroC PRO for AVR Specifics first For language issues you can always refer to the comprehensive Language Reference A complete list of included libraries is available at mikroC PRO for AVR Libraries If you are not very experienced in C programming don t panic mikroC PRO for AVR provides plenty of examples making it easy for you to go quickly We suggest that you first consult Projects and Source Files and then start browsing the exam ples that you re the most interested in MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 3 CHAPTER 1 Introduction mikroC PRO for AVR 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 mikroElek tronika mikroElektronika Associates for software product Software identified above including any software media and accompanying on line or printed docu mentation BY INSTALLING COPYING OR OTHERWISE USING SOFTWARE YOU AGREE TO BE BOUND BY ALL TERMS AND CONDITIONS OF THE LICENSE AGREEMENT Upon your acceptance of the terms and conditions of the License Agreement mikroElektronika Associates grants you the right to use Software in a way provided below This Softw
386. n The declarations asm and _ asm are also allowed in the mikroC PRO for AVR 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 asm asm block of assembly instructions There are two ways to embeding single assembly instruction to C code asm assembly instruction and asm assembly instruction Note semicolon and LF are terminating asm scope for single assembly instructions This is the reason why the following syntax is not asm block asm block of assembly instructions This code will be interpreted as single empty asm line followed by C compound statement The mikroC PRO for AVR 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 g_var of type char i e 1 byte can be accessed like this STS var 0 R10 If you want to know details about asm syntax supported by mikroC PRO for AVR it is recomended to study asm and 1st files generated by compiler It is also recomended to check Include source lines in output files checkbox in Output settings Related topics mikroC PRO for AVR specifcs MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 185
387. n GLCD Prototype 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 6963 and T6963C_WHITE Toshiba GLCD module needs to be initialized See the T6963C_Init routine T6963C_Circle Description Prototype void T6963C Circle int x int y long r unsigned char pcolor Draws a circle on GLCD Parameters Description x X coordinate of the circle center y y coordinate of the circle center r radius size pcolor color parameter Valid values T6963C BLACK and T6963C WHITE Toshiba GLCD module needs to be initialized See the T6963C Init routine Pide ine 120 64 110 T6963C WHITE 516 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries T6963C_Image Prototype void T6963C Image const code char pic Displays bitmap on GLCD Parameters pic image to be displayed Bitmap array can be located in both code Description and RAM memory due to the mikroC PRO for AVR pointer to const and pointer to RAM equivalency Use the mikroC PRO s integrated GLCD Bitmap Editor menu option Tools GLCD Bitmap Editor to convert image to a constant array suitable for display ing on GLCD T
388. n returns the hyperbolic sine of x defined mathematically as 2 If Description the value of x is too large if overflow occurs the function fails sqrt Prototype Function returns the non negative square root of x 548 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries tan Prototype double tan double x Description Function returns the tangent of x in radians The return value spans the allowed P range of floating point in the mikroC PRO for AVR tanh Prototype double tanh double x Function returns the hyperbolic tangent of x defined mathematically as sinh x cosh x Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 549 CHAPTER 6 Libraries mikroC PRO for AVR ANSI C STDLIB LIBRARY The mikroC PRO for AVR provides a set of standard ANSI C library functions of general 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 AVR programming Be sure to skim through the description before using standard C functions Library Functions abs atof atoi atol div div uldiv labs max min rand srand xtoi abs Prototype Function returns the absolute i e positive value of a atof Protot
389. n t need to reply to the UDP requests just define this function with a return 0 as single statement 2 Parameters Description remoteHost Client s IP address remotePort Client s port destPort port to which the request is 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 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 ave mini Ethernet library the board will reply to ARP amp ICMP echo requests the board will reply to UDP requests on any port returns the request in upper char with a header made of remote host IP amp port number the board will reply to HTTP requests on port 80 GET method with pathnames will return the HTML main page s will return board status as text string t7 will toggle P3 b0 to P3 b7 bit and return HTML main page all other requests return also HTML main page 444 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries duplex config flags define Spi Ethernet HALFDUPLEX 0x00 half duplex define Spi Ethernet FULLDUPLEX 0x01 full duplex mE ehternet NIC pinout sfr sb
390. n the array For more information refer to Arrays Automatic Initialization The mikroC PRO for AVR does not provide automatic initialization for objects Uninitial ized globals and objects with static duration will take random values from memory 186 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference 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 Linkag
391. n unchanged input parameter 544 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries ANSI C MATH LIBRARY The mikroC PRO for AVR provides a set of standard ANSI C library functions for floating 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 AVR program ming Be sure to skim through the description before using standard C functions Library Functions acos asin atan atan2 ceil COS cosh eval_poly exp fabs floor frexp Idexp log log10 modf pow sin sinh sqrt tan tanh MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 545 CHAPTER 6 Libraries mikroC PRO for AVR acos Prototype double acos double x Function returns the arc cosine of parameter x that is the value whose cosine Description is x The input parameter x must be between 1 and 1 inclusive The return value is in radians between 0 an inclusive asin Prototype double asin double x Function returns the arc sine of parameter x that is the value whose sine is x Description The input parameter x must be between 1 and 1 inclusive The return value is in radians between 2 and 2 inclusive atan Prototype
392. nd Zendif 225 Directives ifdef and Zifndef 226 XIV MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Table of Contents CHAPTER 6 Hardware AVR specific Libraries 228 Standard ANSI C Libraries 229 Miscellaneous Libraries 229 Library Dependencies 229 ADC Libra ares ie ad eh A 231 ADC Read uia ce E RR 231 Library Example ee bee a E x tena 232 HW Connection 233 CANSPI Library 234 External dependecies of CANSPI Library 235 Library Routines 235 CANSPISetOperationMode 236 CANSPIGetOperationMode 236 CANSPIllnitialize 237 CANSPISetBaudRate 239 CANSPISetMask 240 CANSPISetFilter 241 CANSPIRead 242 LE ed Ra ute qr
393. nderRST at PORTB BO sbit SPExpanderCS at PORTB B1 sbit SPExpanderRST Direction at DDRB BO sbit SPExpanderCS Direction at DDRB B1 End Port Expander module connections void Delay2s 2 seconds delay function Delay 2000 void main char someText char counter MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 465 CHAPTER 6 Libraries mikroC PRO for AVR fu 25 fo 466 MIKROELE If Port Expander Library uses SPI1 module SPI1_ Init Advanced SPI MASTER SPI FCY DIV2 SPI HI TRAIL G Initialize SPI module used with PortExpander SPI Rd Ptr 5 1 Read Pass pointer to SPI Read nction of used SPI module If Port Expander Library uses SPI2 module Initialize SPI module used with PortExpander SPI2 Init Advanced _SPI_ MASTER SPI DIV2 PI CLK HI TRAILING Pass pointer to SPI Read function of used SPI module SPI Rd Ptr amp SPI2 Read SPI Glcd Init 0 Initialize Glcd via SPI SPI Glcd Fill 0x00 Clear Glcd while 1 SPI Glcd Image truck bmp Draw image Delay2s Delay2s SPI Glcd Fill 0x00 Clear Glcd Delay2s SPI Glcd Box 62 40 124 56 1 Draw box SPI Glcd Rectangle 5 5 84 35 1 Draw rectangle SPI Glcd Line 0 63 127 0 1 Draw line Delay2s for counter 5 counter lt 60 counter4 5 Draw horizontal d vertical line Delay ms 250 SPI Gled
394. ne SO PWM Stop Prototype Stops the PWM MCU must have CMO module to use this library PWM Init and PWM Start must be called before using this routine using this routine otherwise it will have no effect as the PWM module is not running 376 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Note Not all the AVR MCUs support both PWM and PWM1 library The best way to verify this is by checking the datasheet for the desired MCU Also you can check this by selecting a MCU in mikroC PRO for AVR looking at the Library Manager If library manager loads both PWM and PWM1 library you are able to check them then this MCU supports both PWM libraries Here you can take full advantage of our Code Assistant and Parameter Assistant feature of our compiler PWM Init Prototvpe void PWM1 Init unsigned short wave mode unsigned short prescaler unsigned short inverted unsigned short duty Initializes the PWM module Parameter wave mode is a desired PWM mode There are two modes Phase Correct and Fast PWM Parameter prescaler chooses prescale value N 1 8 64 256 or 1024 some modules support 32 and 128 but for this you will need to check the datasheet for the desired MCU Paremeter inverted is for choosing between inverted and non inverted PWM signal Parameter duty sets duty ratio from 0 to 255 PWM signal graphs and formulas are shown below PHASE f fak i o
395. ned There is no restriction on the type or offset of members with the same member name in different structures 4 Variables typedefs functions and enumeration members must be unique within the scope in which they are defined Externally declared identifiers must be unique among externally declared variables Duplicate names are legal for different name spaces regardless of the scope rules For example int blue 73 open a block enum colors black red green blue violet white c enumerator blue 3 now hides outer declaration of int blue struct colors int i j ILLEGAL colors duplicate tag double red 2 ILLEGAL redefinition of red blue 37 back in int blue scope 146 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference DURATION Duration closely related to a storage class defines a period during which the declared identifiers have real physical objects allocated in memory We also 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 is allocated to objects with static duration as soon as execution is under way this storage allocation lasts until the program terminates Static duration objects usually reside in fixed data segments a
396. need to be attached to RS 485 interface transceiver such as LTC485 or similar see schematic at the bottom of this page Library constants START byte value 150 STOP byte value 169 Address 50 is the broadcast address for all Slaves packets containing address 50 will be received by all Slaves except the Slaves with addresses 150 and 169 Note Prior to calling any of this library routines UART Wr Ptr needs to be ini tialized with the appropriate UART Write routine Prior to calling any of this library routines UART Rd Ptr needs to be ini tialized with the appropriate UART Read routine Prior to calling any of this library routines Ptr needs to be ini tialized with the appropriate UART_Ready routine Prior to calling any of this library routines TX Idle Ptr needs to be initialized with the appropriate UART TX Idle routine External dependencies of RS 485 Library The following variable must be defined in all projects using RS 485 Library Description Control 5 485 Trans extern sfr sbit sbit RS485 rxtx pin RS485 rxtx pin 2 at PORTD B2 g I mode extern sfr sbit RS485 rxtx pin direc tion Direction of the RS 485 Spit RS485 rxtx pin direc Transmit Receive pin tion at DDRD B2 390 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Library Routines RS485Master_Init
397. nt delimiter symbols is replaced by one space after macro expansion In the mikroC PRO for AVR int type i identifier parses as ine 504 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 123 CHAPTER 5 Language Reference mikroC PRO for AVR 124 Note that the mikroC PRO for AVR does not support a nonportable token pasting strategy using For more information on token pasting refer to the Preprocessor Operators C comments The mikroC PRO for AVR 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 gg parses as IDE int 35 Nested comments ANSI C doesn t allow nested comments The attempt to nest a comment like this ant declaration i fails because the scope of the first ends at the first This gives us a which would generate a syntax error MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference TOKENS Token is the smallest element of a C program that compiler can recognize The parser separates tokens from the input stream by creating the longest token possi ble using the input characters in a left to right scan The mikroC PRO for AVR recognizes the following kinds of tokens keywords identifiers constants operators punctu
398. number by the denom Description inator denom the function returns a structure of type div_t comprising quotient quot and remainder rem see Div Structures Idiv Prototype ldiv_t ldiv long number long denom Function is similar to the div function except that the arguments and result structure members all have type long Description Function computes the result of division of the numerator number by the denom inator denom the function returns a structure of type 1 iv t comprising quotient quot and remainder rem see Div Structures MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 551 CHAPTER 6 Libraries mikroC PRO for AVR uldiv Prototype uldiv t uldiv unsigned long number unsigned long denom Function is similar to the div function except that the arguments and result structure members all have type unsigned long Desenpubn Function computes the result of division of the numerator number by the denom inator denom the function returns a structure of type uldiv_t comprising quo tient quot and remainder rem see Div Structures labs PISOS Function returns the absolute i e positive value of long integer x max piers Function returns greater of the two integers a and b min Prototype Function returns lower of the two integers a and b rand Prototype int rand Function returns a sequence of pseudo random numbers between 0 and 3276
399. nvironmental damage High Risk Activities mikroElektron ika Associates and its suppliers specifically disclaim any expressed or implied war ranty of fitness for High Risk Activities GENERAL PROVISIONS This statement may only be modified in writing signed by you and an authorised offi cer of mikroElektronika Associates If any provision of this statement is found void or unenforceable the remainder will remain valid and enforceable according to its terms If any remedy provided is determined to have failed for its essential purpose all limitations of liability and exclusions of damages set forth in the Limited Warran ty shall remain in effect This statement gives you specific legal rights you may have others which vary from country to country mikroElektronika Associates reserves all rights not specifically granted in this statement mikroElektronika Visegradska 1A 11000 Belgrade Europe Phone 381 11 36 28 830 Fax 381 11 36 28 831 Web www mikroe com E mail office mikroe com 6 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 1 mikroC PRO for AVR Introduction TECHNICAL SUPPORT In case you encounter any problem you are welcome to our support forums at www mikroe com forum Here you may also find helpful information hardware tips and practical code snippets Your comments and suggestions on future develop ment of the mikroC PRO for AVR are always appreciated feel free t
400. o drop a note or two on our Wishlist In our Knowledge Base www mikroe com en kb you can find the answers to Fre quently Asked Questions and solutions to known problems If you can not find the solution to your problem in Knowledge Base then report it to Support Desk www mikroe com en support In this way we can record and track down bugs more efficiently which is in our mutual interest We respond to every bug report and ques tion in a suitable manner ever improving our technical support MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 7 CHAPTER 1 Introduction mikroC PRO for AVR HOW TO REGISTER The latest version of the mikroC PRO for AVR is always available for downloading from our website It is a fully functional software libraries examples and compre hensive help included The only limitation of the free version is that it cannot generate hex output over 2 KB Although it might sound restrictive this margin allows you to develop practical working applications with no thinking of demo limit If you intend to develop really complex projects in the mikroC PRO for AVR then you should consider the possi bility of purchasing the license key Who Gets the License Key Buyers of the mikroC PRO for AVR are entitled to the license key After you have completed the payment procedure you have an option of registering your mikroC PRO In this way you can generate hex output without any limitations How to G
401. o use This file is placed in the compiler s Defs folder DriveName Program Files Mikroelektronika mikroC PRO for AVR Defs and it is named NAME mlk for example ATMEGA16 mlk 7 Add 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 10 Example Library Should appear in the Library manager window Multiple Library Versions Library Alias represents unique name that is linked to corresponding Library mc1 file For example UART library for 16 is different from UART library for ATMEGA128 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 96 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER mikroC PRO for AVR Specifics The following topics cover the specifics of mikroC PRO for AVR compiler ANSI Standard Issues Predefined Globals and Constants Accessing Individual Bits Interrupts AVR Pointers Linker Directives Built in Routines
402. ocessor directives null directive if define ifdef elif ifndef else include endif line error 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 define MACRO This directive continues to the following line MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 219 CHAPTER 5 Language Reference mikroC PRO for AVR MACROS Macros provide 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 is sometimes called the body of a macro An empty token sequence results in the removal of each affected macro identifier from the source code No semicolon is needed to terminate a preprocessor directive Any character found in the token sequence including semicolons will appear in a macro expan sion token sequence terminates at the first non backslashed new line encoun tered Any sequence of whitespace including comment
403. ode Template by typing the name of the template for instance whiles then press Ctr 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 are or click the Show Options Icon and then select the Auto Complete Tab Here you can enter the appropriate keyword description and code of your template Autocomplete macros can retreive system and project information DATES current system date TIMES Current system time DEVICES device MCU name as specified in project settings DEVICE CLOCKS clock as specified in project settings COMPILERS current compiler version H EV EV These macros be used template code see template ptemplate provided with mikroC PRO for AVR installation Auto Correct The Auto Correct feature corrects common typing mistakes To access the list of rec a ognized typos select Tools Options from the drop down menu or click the Show Options Icon and then select the Auto Correct Tab You can also add your own preferences to the list MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 43 CHAPTER 2 Environment mikroC PRO for AVR Also the Code Editor has a feature to comment or uncomment the selected code by simple click of a mouse using the Comment Icon and Uncomment Icon
404. ode in which transmission is possible See CANSPISetOperationMode The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page send message extended CAN message with the appropriate ID and tx flags data 8 msg id CANSPISetOperationMode CAN 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 CANSPIWrite msg id data 2 tx flags IKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 243 CHAPTER 6 Libraries mikroC PRO for AVR CANSPI Constants There is a number of constants predefined in the CANSPI library You need to be familiar with them in order to be able to use the library effectively Check the exam ple at the end of the chapter CANSPI_OP_MODE The CANSPI_OP_MODE constants define CANSPI operation mode Function CANSPISetOperationMode expects one of these as it s argument const char CANSPI MODE BITS OxEO Use this to access opmode bits CANSPI MODE NORMAL 0x00 CANSPI MODE SLEEP 0x20 CANSPI MODE LOOP 0x40 CANSPI MODE LISTEN 0x60 CANSPI MODE CONFIG 0x80 CANSPI_CONFIG_FLAGS The CANSPI CONFIG FLAGS constants define flags related to the CANSPI mod ule configurat
405. olor highlighted blue by default Note The Software Simulator simulates the program flow and execution of instruc tion lines but it cannot fully emulate AVR device behavior i e it doesn t update timers interrupt flags etc Watch Window The Software Simulator Watch Window is the main Software Simulator window which allows you to monitor program items while simulating your program To show the Watch Window select View Debug Windows Watch from the drop down menu The Watch Window displays variables and registers of the MCU along with their addresses and values There are two ways of adding variable register to the watch list by its real name variable s name in C code Just select desired vari able register from Select variable from list drop down menu and click the Add Button by its name ID assembly variable name Simply type name ID of the vari able register you want to display into Search the variable by assemby name box and click the Add Button Variables can also be removed from the Watch window just select the variable that you want to remove and then click the Remove Button Remove MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 91 CHAPTER 2 Environment mikroC PRO for AVR Add All Button Add All adds all variables Remove All Button Remove removes all variables You can also expand collapse complex variables i e struct typ
406. ols Options from the drop down menu click the Show Options Icon at or press F12 key 40 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR CHAPTER 2 Editor Settings Editor Colors Auto Correct Auto Complete w Style variable variable variable variable Project Files V Restore Last Opened Project V Save Breakpoints V Save Bookmarks If Opened File Is Externally Modified Prompt for action Reload file but do not prompt Ignore externally made changes Auto Save V Enable Auto Save Timeout Interval 3 minutes Highlighter F Highlight begin end pairs Highlight brackets Spelling E V Check Spelling style I inge ine sfr unsigned char SPDR s r unsigned char SPSR sfr unsigned char SPCR Advanced Editor Options Open options dialog Code Assistant If you type the first few letters of a word and then press Ctri Space all valid identi fiers matching the letters you have typed will be prompted in a floating panel see the image below Now you can keep typing to narrow the choice or you can select one from the list using the keyboard arrows and Enter unsigned char SP MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD Environment 41 CHAPTER 2 Environment mikroC PRO for AVR Code Folding Code folding is IDE feature which allows users to select
407. on Parameters ptr String to be written into zxc28760 RAM Ethernet module has to be initialized See SPI Ethernet Init char buffer mikroElektronika SPI Ethernet putString buffer put a RAM string into ENC28J60 buffer 440 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI_Ethernet_putConstString unsigned int SPI Ethernet putConstString const unsigned char Prototype Number of bytes written into ENc28760 RAM This is MAC module routine It stores whole const string excluding null termina tion into ENC28J60 RAM starting from current ENC28J60 write pointer EWRPT location Description Parameters ptr const string to be written into zxc28760 RAM Requires Ethernet module has to be initialized See SPI Ethernet Init const char buffer mikroElektronika SPI Ethernet putConstString buffer put a const string into ENC28J60 buffer SPI Ethernet getByte Prototype unsigned char SPI Ethernet getByte Returns Byte read from ENc28760 RAM This is MAC module routine It fetches a byte from address pointed to by current Description ENC28J60 read pointer ERDPT Ethernet module has to be initialized See SPI Ethernet Init char buffer buffer SPI Ethernet getByte read a byte from ENC28J60 buffer MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUT
408. ontOffs is 20 Demo fonts supplied with the library have an off set of 32 which means that they start with space The user can use fonts given in the file Lib GLCDFonts file located in the Uses folder or create his own fonts Requires Glcd needs to be initialized see Glcd Init routine Use the custom 5x7 font myfont which starts with space 32 Gled Set Font myfont 5 7 32 292 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Glcd Write Char void Glcd Write Char unsigned short chr unsigned short x pos unsigned short page num unsigned short color Nothing Prints character on the Glcd Prototype Parameters chr character to be written x pos character starting position on x axis Valid values 0 127 Font Width page num the number of the page on which character will be written Valid values 0 7 color color parameter Valid values 0 2 Description The parameter color determines the color of the character 0 white 1 black and 2 inverts each dot Note For x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized see Glcd Init routine Use Glcd Set Font to specify the font for display if no font is specified then default 5x8 font supplied with the library will be used Write character C on the position 10 inside the page 2 Gled Write Char C 10 2
409. onth unsigned short day unsigned short hours unsigned short mins Reads time date attributes of currently assigned file Parameters year buffer to store year attribute to Upon function execution year attribute is returned through this parameter month buffer to store month attribute to Upon function execution month attribute is returned through this parameter day buffer to store day attribute to Upon function execution day attrib ute is returned through this parameter hours buffer to store hours attribute to Upon function execution hours attribute is returned through this parameter nins buffer to store minutes attribute to Upon function execution min utes attribute is returned through this parameter Description CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign unsigned year char month day hours mins Cf Fat Get File Date amp year amp month amp day amp hours amp mins MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 265 CHAPTER 6 Libraries mikroC PRO for AVR Cf_Fat_Get_File_Size Returns Size of the currently assigned file in bytes This function reads size of currently assigned file in bytes CF card and CF library must be initialized for file operations See Cf Fat Init File must be previously assigned See Cf Fat Assign unsigned long my file
410. operations See Cf Fat Init File must be previously assigned See Cf Fat Assign File must be open for writing See Cf Fat Rewrite or Cf Fat Append char file contents 42 Cf Fat Write file contents 42 write data to the assigned file MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 263 CHAPTER 6 Libraries mikroC PRO for AVR Cf_Fat_Set_File_Date void Cf Fat Set File Date unsigned int year unsigned short month unsigned short day unsigned short hours unsigned short mins unsigned short seconds Sets the date time stamp Any subsequent file writing operation will write this stamp to currently assigned file s time date attributs Parameters Description year year attribute Valid values 1980 2107 month month attribute Valid values 1 12 day day attribute Valid values 1 31 hours hours attribute Valid values 0 23 mins minutes attribute Valid values 0 59 seconds seconds attribute Valid values 0 59 CF card and CF library must be initialized for file operations See Cf_Fat_Init File must be previously assigned See Cf_Fat_Assign File must be open for writing See Cf_Fat_Rewrite or Cf_Fat_Append Example Set Pile Date 2005 9 30 17 41 0 264 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Cf_Fat_Get_File_Date void Cf Fat Get File Date unsigned int year unsigned short m
411. or AVR Libraries Expander_Write_PortB Prototype void Expander Write PortB char ModuleAddress char Data The function writes byte to Port Expander s PortB Parameters Description ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written Port Expander must be initialized See Expander Init Port Expander s PortB should be configured as output See Expander_Set_DirectionPortB and Expander_Set_DirectionPortAB routines Write a byte to Port Expander s PORTB Expander Set DirectionPortB 0 0x00 set expander s portb to be output Expander Write PortB 0 0x55 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 359 CHAPTER 6 Libraries mikroC PRO for AVR Expander_Write_PortAB void Expander Write PortAB char ModuleAddress unsigned int Data The function writes word to Port Expander s ports Prototype Parameters Description 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 Port Expander must be initialized See Expander Init Port Expander s PortA and PortB should be configured as outputs See Expander Set DirectionPortA Expander Set DirectionPortB and Expander Set DirectionPortAB routines Write a byte to Port Ex
412. or SPI communication see SPI Glcd Init routine Draw a circle with center in 50 50 and radius 10 SPI Gled C rrcle 50 50 10 1 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 461 CHAPTER 6 Libraries mikroC PRO for AVR SPI Glcd Set Font Prototvpe void SPI Glcd Set Font const code char activeFont char yp aFontWidth char aFontHeight unsigned int aFontOffs Sets font that will be used with SPI Glcd Write Char and SPI Glcd Write Text routines Parameters activeFont font to be set Needs to be formatted as an array of char aFontWidth Width of the font characters in dots Description aFontHeight height of the font characters in dots aFontOffs number that represents difference between the mikroC PRO character set and regular ASCII set eg if A is 65 in ASCII character and A is 45 in the mikroC PRO character set aFontOffs is 20 Demo fonts supplied with the library have an offset of 32 which means that they start with space The user can use fonts given in the file Lib Glcd fonts file located in the Uses folder or create his own fonts Requires Glcd needs to be initialized for SPI communication see SPI Glcd Init routines Use the custom 5x7 font myfont which starts with space 32 SPI Glcd Set Font myfont 5 7 32 462 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI_Glcd_Write_Char
413. or is unde fined to string must have enough space to store the result The function returns address of the object pointed to by to char strchr char ptr char chr Function locates the first occurrence of character chr in the string ptr The function returns a pointer to the first occurrence of character cnr or a null point er if chr does not occur in ptr The terminating null character is considered to be a part of the string int strcmp char s1 char s2 Function compares strings s1 and s2 and returns zero if the strings are equal or returns a difference between the first differing characters in a left to right evaluation Accordingly the result is greater than zero if 51 is greater than 52 and vice versa char strcpy char to char from Function copies the string from into the string co If copying is successful the function returns to If copying takes place between objects that overlap the behavior is undefined int strlen char s Function returns the length of the string s the terminating null character does not count against string s length 556 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries strncat Prototype char strncat char to char from int size Function appends not more than size characters from the string from to to The Description initial character of from overwrites the null character at the end of to
414. or to top left SPI T6963C cursor 0 cursor off Draw rectangles SPI T6963C rectangle 0 0 239 127 SPI T6963C WHITE SPI T6963C rectangle 20 20 219 107 SPI T6963C WHIT SPI T6963C rectangle 40 40 199 87 SPI T6963C WHITE SPI T6963C rectangle 60 60 179 67 SPI T6963C WHITE Draw cross SPI T6963C 1 0 0 239 127 SPI T6963C WHITE SPI T6963C line 0 127 239 0 SPI T6963C WHITE Draw solid boxes af SPI T6963C box 0 0 239 8 SPI T6963C WHITE SPI T6963C box 0 119 239 127 SPI T6963C WHITE Draw circles A PI T6963C circle 120 64 10 SPI T6963C WHIT PI T6963C circle 120 64 30 SPI T6963C WHIT PI T6963C circle 120 64 50 SPI T6963C WHIT PI T6963C circle 120 64 70 SPI T6963C WHIT Ed bd pH pd PI T6963C circle 120 64 90 SPI T6963C WHITI PI T6963C circle 120 64 110 SPI T6963C WHITI PI T6963C circle 120 64 130 SPI T6963C WHITI d 0 d SPI T6963C sprite 76 4 einstein 88 119 Draw a sprite SPI T6963C setGrPanel 1 Select other graphic panel SPI T6963C image me Fill the graphic screen with a picture while 1 Endless loop 502 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries If 0 is pressed toggle the display
415. oshiba GLCD module needs to be initialized See the T6963C Init routine 55 32 T6963C_Sprite void T6963C Sprite unsigned char px unsigned char py const code Prototype xc r char pic unsigned char sx unsigned char sy Fills graphic rectangle area px py to px sx with custom size picture Parameters px X coordinate of the upper left picture corner Valid values multiples of the font width Description py y coordinate of the upper left picture corner pic picture to be displayed sx picture width Valid values multiples of the font width sy picture height 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 Toshiba GLCD module needs to be initialized See the T6963C Init routine Example 16963 sprite 76 4 einstein 88 119 draw a sprite MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 517 CHAPTER 6 Libraries mikroC PRO for AVR T6963C_Set_Cursor Prototype void T6963C Set Cursor unsigned char x unsigned char y Sets cursor to row x and column y Parameters Description x Cursor position row number y Cursor position column number Toshiba GLCD module needs to be initialized See the T6963C Init routine Ee T6963C Set Cursor cposx cposy T6963C ClearBit Clears control port bit s Parameters Description
416. ot 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 i 0 decimal 0 octal 0 In the absence of any overriding suffixes the data type of a decimal constant is derived from its value as shown below MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 127 CHAPTER 5 Language Reference mikroC PRO for AVR Value Assigned to Constant Assumed Type lt 2147483648 Error Out of range 2147483648 32769 32768 129 int 256 32767 int 32768 65535 Hexadecimal All constants starting with 0x or 0x are taken to be hexadecimal In the absence of any overriding suffixes the data type of an hexadecimal constant is derived from its value according to the rules presented above For example 0xc367 will be treated aS unsigned int Binary All constants starting with 0b or are taken to be binary In the absence of any over riding suffixes the data type of an binary constant is derived from its value according to the rules presented above For example 0511101 will be treated as short Octal All constants with an initial zero are taken to be octal If an octal constant contains the illegal digits 8 or 9 an error is reported In the absence of any overriding suffix es the data type of an octal constant is derived from its value according to the rules presente
417. outines The function must return the length in bytes of the TCP HTTP reply or 0 if there is nothing to transmit If there is no need to reply to the TCP HTTP requests just define this function with return O as a single statement FOR Parameters Description remoteHost client s IP address remotePort Client s TCP port localPort port to which the request is sent reqLength TCP HTTP request data field length Note The function source code is provided with appropriate example projects The code should be adjusted by the user to achieve desired reply Ethernet module has to be initialized See SPI Ethernet Init This function is internally called by the library and should not be called by the user s code MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 443 CHAPTER 6 Libraries mikroC PRO for AVR SPI_Ethernet_UserUDP unsigned int SPI Ethernet UserUDP unsigned char remoteHost Prototype unsigned int remotePort unsigned int destPort unsigned int reqLength 0 there should not be a reply to the request Length of UDP reply data field otherwise This is UDP module routine It is internally called by the library The user accesses to the UDP request by using some of the SPI Ethernet get routines The user puts data in the transmit buffer by using some of the SPI Ethernet put routines The function must return the length in bytes of the UDP reply or 0 if nothing to transmit If you do
418. pander s PORTA and PORTB Expander Set DirectionPortAB 0 0x0000 set expander s porta and portb to be output Expander Write PortAB 0 55 360 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Expander_Set_DirectionPortA Prototype void Expander Set DirectionPortA char ModuleAddress char Data Nothing 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 corre sponds to the appropriate pin of the PortA register Set bit designates corresponding pin as input Cleared bit designates corresponding pin as output Requires Port Expander must be initialized See Expander Init Set Port Expander s PORTA to be output Expander Set DirectionPortA 0 0x00 Description Expander Set DirectionPortB Prototype void Expander Set DirectionPortB char ModuleAddress char Data Nothing The function sets Port Expander s PortB direction Parameters T ModuleAddress Port Expander hardware address see schematic at Description the bottom of this page Data data to be written to the PortB direction register Each bit corre sponds to the appropriate pin of the PortB register Set bit designates corresponding pin as input Cleared bit designates correspondin
419. pare 27 Write reads data from it and puts To read file procedure 342 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries for i 1 i lt size itt Mmc Fat Read amp caracter UART1 Write caracter Write data to USART M M M Deletes a file If file doesn t exist it will first be created and then deleted void M Delete File filename 7 F Mmc Fat Assign filename 0 Mmc Fat Delete M M M Tests whether file exists and if so sends its cre ation date and file size via USART void M Test File Exist unsigned long fsize unsigned int year unsigned short month day hour minute unsigned char outstr 12 filename 7 B uncomment this line to search for file that DOES exists filename 7 F uncomment this line to search for file that DOES NOT exist if Mmc Fat Assign filename 0 file has been found get its date Mmc Fat Get File Date amp year amp month amp day amp hour amp minute WordToStr year outstr I Write Str outstr ByteToStr month outstr I Write Str outstr WordToStr day outstr I Write Str outsttr WordToStr hour outstr I Write Str outstr WordToStr minute outstr I Write Str outstr get file size fsize Mmc Fat Get File Size LongToStr signed long fsize outstr I Write Str outstr MIKROELE
420. ple if we have an expression amp amp b amp amp c where ais false 0 then operands b and c Will not be evaluated This is very important if 5 and c are expressions as their possible side effects will not take place LOGICAL VS BITWISE Be aware of the principle difference between how bitwise and logical operators work For example 0222222 amp 0555555 equals 000000 0222222 amp amp 0555555 equals 1 0x1234 equals OxEDCB 0x1234 equals 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 201 CHAPTER 5 Language Reference mikroC PRO for AVR 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 expression evaluates and expression3 is ignored If expressioni 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 Find max a b max a gt b Convert small letter to capital no parentheses are actually necessary c
421. plementation 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 in bytes of any standard or user defined type The mikroC PRO for AVR standard libraries and your own program and header files must provide unambiguous identifiers or expressions derived from them and types so that the mikroC PRO for AVR can consistently access interpret and possibly change the bit patterns in memory corresponding to each active object in your pro gram 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 149 CHAPTER 5 Language Reference mikroC PRO for AVR FUNDAMENTAL TYPES The fudamental types represent types that cannot be divided into
422. ples PORTA matches string PonTA only if it s at the beginning of line PORTAS matches string PORTA only if it s at the end of line PORTAS matches string PORTA only if it s the only string in line PORT r matches strings like PoRTA PORTB PoRT1 and so on The metacharacter by default is only guaranteed to match beginning of the input string text and the s metacharacter only at the end Embedded line separators will not be matched by or s You may however wish to treat a string as a multi line buffer such that the will match after any line separator within the string and s 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 NW a nonalphanumeric Nd a numeric character D a non numeric Vs any space same as t n r fl NS a non space You may use w d and s within custom character classes Example routi de matches strings like rout ile routi6e and so on but not routine routime and so on MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 71 CHAPTER 2 Environment 72 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Metacharacters Word boundaries A word boundary b is a spot b
423. printi Prototype sprinti char wh const char f Returns The 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 571 CHAPTER 6 Libraries mikroC PRO for AVR Library Example This is 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 2587538e 41 char buffer 15 Function for sending string to UART void UartWriteText char txt while txt Uart Write txt Function for sending const string to UART void UartWriteConstText const char txt while txt Uart Write txt void main 4800 Initialize UART mod ule at 4800 bps Delay ms 10 UartWriteConstText Floating point number representation Write message on UART sprintf buffer 12e ww Format ww and store it to buffer UartWriteConstText r ne format Write message on UART UartWriteText buffer Write buffer on UART sprintf buffer 12 ww Format ww and store it to buffer UartWriteConstText r nf format Write message on UART UartWriteText buffer Write buffer on UART sprintf buffer 12g ww Form
424. r more information 182 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference TYPE QUALIFIERS The type qualifiers const and volatile are optional in declarations and do not actually affect the type of declared object Qualifier const The qualifier const implies that a declared object will not change its value during runtime In declarations with the const qualifier all objects need to be initialized The mikroC PRO for AVR treats objects declared with the const qualifier the same as literals or preprocessor constants If the user tries to change an object declared with the const qualifier compiler will report an error For example const double PI 3 14159 Qualifier volatile The 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 183 CHAPTER 5 Language Reference mikroC PRO for AVR TYPEDEF SPECIFIER The specifier t ypedef introduces a synonym for a specified type The typedef dec larations are use
425. r of the text 0 white 1 black and 2 inverts each dot Note For x axis and page layout explanation see schematic at the bottom of this page Glcd needs to be initialized for SPI communication see SPI Glcd 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 Write text Hello world on the position 10 inside the page 25 SPI Glcd Write Text Hello world 464 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI Glcd Image Prototype void SPI Glcd Image const code char image Nothing Displays bitmap on Glcd Parameters Description image image to be displayed Bitmap array can be located in both code and RAM memory due to the mikroC PRO for AVR pointer to const and pointer to RAM equivalency Use the mikroC PRO 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 Glcd Init routines Draw image my image on Glcd SPI Glcd Image my image Library Example The example demonstrates how to communicate to KS0108 Glcd via the SPI module using seri al to parallel convertor 23517 const code char truck bmp 1024 Port Expander module connections sbit SPExpa
426. ral 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 s from the Project Manager window The project group may be reopend by clicking the Open Project Group Icon MN All relevant data about the project group is stored in the project group file extension mpgroup Add Remove Files from Project The project can contain the following file types source files h header files mcl binary files pld project level defines files image files hex asm and ist files see output files These files can not be added or removed from project other files 80 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment lll 4 7 LedBlinking mcpav 4 Sources 2 LedBlinking c Header Files 73 Binaries E Project level defines Image Files 4 Output Files LedBlinking hex 2 LedBlinking asm 2 LedBlinking Ist E Other Files The list of relevant source files is stored in the project file extension mcpav To add source file to the project click the Add File to Project Icon l Each added source file must be self contained i e it must have all necessary definitions after preprocessing To remove file s from the project click the Remove Fi
427. rameters Description sectors cnt number of consecutive sectors that user wants the swap file to have filename name of the file that should be assigned for file operations The file name should be in DOS 8 3 file name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does not have to take care of that The file name and extension are case insensitive The library will convert them to proper case automatically so the user does not have to take care of that Also in order to keep backward compatibility with the first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between the file name and exten sion i e MIKROELETXT gt MIKROELE TXT In this case the last characters of the string are considered to be file extension file attr creation and attributs flags Each bit corresponds to the appropriate file attribut MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 267 CHAPTER 6 Libraries mikroC PRO for AVR Be ms Been oom Remedy Description 75 Note Long File Names LFN are not supported CF card and CF library must be initialized for file operations See Cf_Fat_Init Try to create a swap file with archive atribute whose size will be at least 1000 sector
428. range 1000 1000 E3 45 result is 707 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 577 CHAPTER 6 Libraries mikroC PRO for AVR cosE3 Prototype int cosE3 unsigned angle deg The function returns the cosine of input parameter The function calculates cosine multiplied by 1000 and rounded to the nearest integer result round cos angle deg 1000 Description Parameters angle deg input angle in degrees Note Return value range 1000 1000 E3 196 result is 193 578 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 579 cms Y Bays ogg m 08 ay e 9 21 9 Jogo 0000 legere 1C OO INI ON Jojo oo 0 QQleocK OO e INS 919 9 51515191 Db _ 0000000 U102 20J 1U49 921JO 0 9 C O O O N QV O SR o Q VS ks VS Oo O O e SEV UV LHOddn s 1 MOU SN ja aseajd uorjeuuojur jeuonippe asnf NOK 51 Aue uM sule qoJd Burueuedxe KII MV IWNe 5 12e1u02 se jd jesodoud ssauisng e
429. ranteed that the dynamic link will be enough for the program execution If this happens dynamic link can get out of its boundaries and overwrite static link ANSI STANDARD ISSUES Divergence from the ANSI C Standard Tentative declarations are not supported C Language Exstensions mikroC PRO for AVR has additional set of keywords that do not belong to the ANSI standard C language keywords code data Nx ac sbit itt Sfr Related topics Keywords AVR Specific 98 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroC PRO for AVR Specifics PREDEFINED GLOBALS AND CONSTANTS To facilitate programming of AVR compliant MCUs the mikroC PRO for AVR imple ments a number of predefined globals and constants All AVR SFR registers and their bits are implicitly declared as global variables These identifiers have an external linkage and are visible in the entire project When creating a project the mikroC PRO for AVR will include an appropriate file from defs folder containing declarations of available SFR registers and constants For a complete set of predefined globals and constants look for Defs in the mikroC PRO for AVR installation folder or probe the Code Assistant for specific letters Ctrl Space the Code Editor Predefined project level defines There are 2 predefined project level defines for any project you make These defines are based on values that yo
430. rates using library routines for Soft SPI communication Also this example demonstrates working with Microchip s MCP4921 12 bit D A converter DAC module connections sbit Chip Select at PORTB BO sbit SoftSpi CLK at PORTB B7 sbit SoftSpi SDI at PINB B6 Note Input signal sbit SoftSpi SDO at PORTB B5 sbit Chip Select Direction at DDRB B0 sbit SoftSpi CLK Direction at DDRB B7 sbit SoftSpi SDI Direction at DDRB B6 sbit SoftSpi SDO Direction at DDRB B5 End DAC module connections unsigned int value void InitMain DDAO 0 Set PAO pin as input DDA1 0 Set 1 pin as input Chip Select 1 Deselect DAC Chip Select Direction 1 Set CS pin as Output Soft SPI Init Initialize Soft SPI DAC increments 0 4095 gt output voltage 0 Vref void DAC Output unsigned int valueDAC char Chip temp Select 0 Send High Byte Select DAC chip Store valueDAC 11 8 temp valueDAC gt gt 8 amp OxO0F to temp 3 0 temp 0x30 see MCP4921 datasheet Soft SPI Write temp Send Low Byte temp valueDAC to temp 7 0 Soft SPI Write temp Chip Select 1 Define DAC setting Send high byte via Soft SPI Store valueDAC 7 0 Send low byte via Soft SPI Deselect DAC chip MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 413 CHAPTER 6 Libraries mikroC PRO for AVR void main Init
431. ration mode codes The CANSPI routines are supported only by MCUs with the SPI module MCU has to be properly connected to mikroElektronika s CANSPI Extra Board or similar hardware See connection example at the bottom of this page check whether the CANSPI module is in Normal mode and if it is do something if CANSPIGetOperationMode CANSPI MODE NORMAL 236 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries CANSPIInitialize void CANSPIInitialize char SJW char BRP char PHSEG1 char PHSEG2 char PROPSEG char CAN CONFIG FLAGS Nothing Initializes the CANSPI module Stand Alone CAN controller in the CANSPI module is set to Disable CAN capture Continue CAN operation in Idle mode Do not abort pending transmissions Fcan clock 4 Tcy Fosc Baud rate is set according to given parameters CAN mode Normal Filter and mask registers IDs are set to zero Filter and mask message frame type is set according to ERE CAN CONFIG FLAGS value Description EG2PHTS DBEN bits are set according to CONFIG FLAGS Parameters 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 CON
432. rations and Declarators 179 LINKAGES 25 2 aba bade qu Rau edd deb bau badd eet eles 180 Linkage Rules 2 ee Rm ea d qnm ee 180 Internal Linkage 180 External Linkage Rules 180 Storage Classes 181 opc 181 Register 222 cedrus dua Ro x e Y C RR Reg S 181 DLAC p Ap 182 Suc MT 182 Type Qualifiers 183 Qualifier Const see 225 eio p Rb pie ied ERR 183 Qualifier volatile 183 Typedef 5 184 asm Declaration aad he D Lad e Ee ee ERE oad 185 Automatic Initialization 186 F tictlons uda Rx ee quee 187 Function Prototypes 188 Function Definition 188 Functions 189 XII MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Table of Contents Function Calls and Argument Conversions 190 Function Calls 5 ean eae ACCES a TOR eee 190 Argument Conversions 191 Operators
433. rator associates from right to left Logical Operators Overview Logical Operations Precedence of logical relational and arithmetic operators was designated in such a way to allow complex expressions without parentheses to have an expected meaning gt Q amp amp lt 9 reads as c gt 0 amp amp c lt TOt 1 f x reads as 1 b L x Logical AND returns 1 only if both expressions evaluate to be nonzero otherwise returns O If the first expression evaluates to false the second expression will not be evaluated For example a gt amp amp lt reads as a b amp amp c d if a gt b is false 0 lt d will not be evaluated Logical OR returns 1 if either of expression evaluates to be nonzero otherwise returns O If the first expression evaluates to true the second expression is not eval uated For example amp amp b c amp amp d reads as a amp amp b c amp amp d if a amp amp b is true 1 c amp amp d will not be evaluated 200 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference 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
434. rease the viewing and editing space for code depending on how you arrange the windows in the IDE Step 1 Click the window you want to dock to give it focus Temm JJ Step 2 Drag the tool window from its current location A guide diamond appears The four arrows of the diamond point towards the four edges of the IDE MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 37 CHAPTER 2 Environment mikroC PRO for AVR Step 3 Move the pointer over the corresponding portion of the guide diamond An outline of the window appears in the designated area Step 4 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 like you can save the layout by typing the name for the layout and pressing the Save Layout Icon To set the layout select the desired layout from the layout drop down list and click the Set Layout icon asi To remove the layout from the drop down list select the desired layout from the list and click the Delete Layout Icon 38 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment Auto Hide Auto Hide enables you to see more of your code at one time by minimizing tool win dows along the edges of the IDE when not in use
435. results in the left to right evaluation of each expression with the value and type of expression 2 giving the result of the whole expression Result of expression 1 is discarded Binary operator comma has the lowest precedence and associates from left to right so thata b cisthe sameas a b c This allows writing sequences with any number of expressions expression 1 expression 2 expression n which results in the left to right evaluation of each expression with the value and type of expression n giving the result of the whole expression Results of other expressions are discarded but their possible side effect do occur For example result 5 b 2 cM returns preincremented value of variable c but also intializes a divides b by 2 and increments c result x 10 y x 3 z 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 fune i G l1 j 4 calls the function func with three arguments i 5 k not four MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 207 CHAPTER 5 Language Reference mikroC PRO for AVR STATEMENTS Statements specify a flow of
436. ried 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 rou tine only the rou part will match as that is the first alternative tried and it suc cessfully matches the target string this might not seem important but it is important when you are capturing matched text using parentheses Also remember that is interpreted as a literal within square brackets so if you write fie foe You re really only matching Examples rou tine te matches strings xoutine Or route MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 73 CHAPTER 2 Environment mikroC PRO for AVR Metacharacters Subexpressions The bracketing construct may also be used for define regular subexpres sions Subexpressions are numbered based on the left to right order of their open ing parenthesis First subexpression has number 1 Examples int 8 10 matches strings which contain 8 9 or 10 instances of the me routi 0 9 at 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 1 matches abab and 123
437. ription void SPI Ethernet Init unsigned char mac unsigned char ip unsigned char fullDuplex Nothing This is MAC module routine It initializes ENc28760 controller This function is internaly splited into 2 parts to help linker when coming short of memory ENC28J60 controller settings parameters not mentioned here are set to default receive buffer start address 0x0000 receive buffer end address 0x19AD transmit buffer start address 0x19AE transmit buffer end address 0x1FFF RAM buffer read write pointers in auto increment mode receive filters set to default CRC MAC Unicast MAC Broadcast in OR mode flow control with TX and RX pause frames in full duplex mode frames are padded to 60 bytes CRC maximum packet size is set to 1518 Back to Back Inter Packet Gap 0x15 in full duplex mode 0x12 in half duplex mode Non Back to Back Inter Packet Gap 0x0012 in full duplex mode 0x0c12 in half duplex mode Collision window is set to 63 in half duplex mode to accomodate some ENC28J60 revisions silicon bugs CLKOUT output is disabled to reduce EMI generation half duplex loopback disabled LED configuration default LEDA link status LEDB link activity Parameters mac RAM buffer containing valid MAC address ip RAM buffer containing valid IP address fullDuplex ethernet duplex mode switch Valid values o half duplex mode and 1 full duplex mo
438. rl Paste text from clipboard elete Delete selected text Select All Ctrl 4 Select all text in active editor T Ctrl F Find text in active editor MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 15 CHAPTER 2 Environment mikroC PRO for AVR Find next occurence of text in active editor Find previous occurence of text in active editor Replace text in active editor 5 Find text in current file in all opened files or in Find In Files a AIL F3 files from desired folder gt Goto Line Ctrl G Goto to the desired line in active editor Advanced Advanced Code Editor options Advanced Description Comment selected code or put single line com ted Comment ment if there is no selection Uncomment selected code or remove single line com Uncomment Shift Ctrl ment if there is no selection Indent selected code Outdent selected code Changes selected text case to lowercase Changes selected text case to uppercase Changes selected text case to titlercase 16 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment Dialog box for searching the document for the specified text The search is per formed in the direction specified If the string is not found a message is displayed Find Text lt x Search for
439. rojects using Sound Library extern sfr sbit Sound output pin sbit Sound Play Pin Sound Play Pin at PORTC B3 extern sfr sbit sbit t Sound Play Pin vised Direction of the Sound ou Sound Play Pin Direct ale put pin x m man Lon ion at DDRC B3 Library Routines Sound Init Sound Play MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 421 CHAPTER 6 Libraries mikroC PRO for AVR Sound Init Prototype Configures the appropriate MCU pin for sound generation Global variables Sound Play Pin Sound output pin Sound Play Pin Direction Direction of the Sound output pin must be defined before using this function Sound library connections sbit Sound Play Pin at PORTC B3 sbit Sound Play Pin direction at DDRC B3 End of Sound library connections Sound Init Sound Play Prototype void Sound Play unsigned freq in hz unsigned duration ms Generates the square wave signal on the appropriate pin Parameters Description freq in hz signal frequency in Hertz Hz duration ms Signal duration in miliseconds ms In order to hear the sound you need a piezo speaker or other hardware on designated port Also you must call Sound Init to prepare hardware for output before using this function Play sound of 1KHz in duration of 100ms Sound Play 1000 100 422 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTE
440. ropagation The compiler recognizes that two variables have the same value and eliminates one of them fur ther in the code Value numbering The compiler recognizes if two expressions yield the same result and can therefore eliminate the entire computation for one of them 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 110 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroC PRO for AVR Specifics 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 Related topics AVR specifics mikroC PRO for AVR specifics Memory type speci fiers MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 111 CHAPTER 3 Specifics mikroC PRO for AVR 112 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER AVR Specifics Types Efficiency First of all you should know that
441. rototype Function returns the absolute i e positive value of a floor Prototype Function returns the value of parameter x rounded down to the nearest integer frexp Prototype double frexp double value int eptr Function splits a floating point value into a normalized fraction and an integral Description power of 2 The return value is the normalized fraction and the integer exponent is stored in the object pointed to by eptr Idexp Prototype double ldexp double value int newexp Function returns the result of multiplying the floating point number num by 2 raised to the power n i e returns x 2n Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 547 CHAPTER 6 Libraries mikroC PRO for AVR log Function returns the natural logarithm of x i e log log10 Function returns the base 10 logarithm of x i e 16945 modf Prototype double modf double val double iptr Returns argument va1 split to the fractional part function return val and integer Description part in number iptr pow Prototype double pow double x double y Function returns the value of x raised to the power y i e xY If x is negative Description the function will automatically cast into unsigned long sin Prototype Function returns the sine of in radians The return value is from 1 to 1 sinh Prototype Functio
442. routines These principles can be explained on the picture below 102 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 3 mikroC PRO for AVR Specifics Interrupt Vector Interrupt Vector Table Table Goto table Direct accessing interrupt service routine and accessing interrupt service routine via Goto table MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 103 CHAPTER 3 Specifics mikroC PRO for AVR LINKER DIRECTIVES The mikroC PRO uses an internal algorithm to distribute objects within memory If you need to have a variable or routine at specific predefined address use the link er directives 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 is 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 0x33 Variable i will occupy 1 byte at address 0x33 long 3113 absolute 0x30 Variable will occupy 4 bytes at 0x30 0x31 0x32 0x33 thus changing i changes jjjj highest byte at the same time and vice versa Directive or
443. rs 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 complex 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 paren theses and data types of the operands The precedence and associativity of the operators are summarized in Operator Precedence and Associativity The way operands and subexpressions are grouped does not necessarily specify the actual order in which they are evaluated by the mikroC PRO for AVR Expressions can produce lvalue rvalue or no value Expressions might cause side effects whether they produce a value or not 206 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference COMMA EXPRESSIONS One of the specifics of C is that it allows using of comma as a sequence operator to form so called comma expressions or sequences Comma expression is a comma delimited list of expressions it is formally treated as a single expression so it can be used in places where an expression is expected The following sequence expression 1 expression 2
444. rsa memcpy Prototype void memcpy void 01 void s1 int n Function copies n characters from the object pointed to by s2 into the object point Description ed to by a1 If copying takes place between objects that overlap the behavior is undefined The function returns address of the object pointed to by a1 memmove Prototype void memmove void to void from register int n Function copies n characters from the object pointed to by from into the object Description 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 memset void pl char character int n yp Function copies the value of the character into each of the first n characters of Description the object pointed by p1 The function returns address of the object pointed to by pl MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 555 CHAPTER 6 Libraries strcat Prototype Description strchr Prototype Description strcmp Prototype Description strcpy Prototype Description strlen Prototype Description mikroC PRO for AVR char strcat char to char from Function appends a copy of the string from to the string to overwriting the null character at the end of to Then a terminating null character is added to the result If copying takes place between objects that overlap the behavi
445. rupt enable TCCRO bit Start timer with 1024 prescaler SREG I 0 Interrupt disable Man Receive Init try Man Receive with blocking prevention mechanism SREG I 1 Interrupt enable datal Man Receive amp error SREG I 0 Interrupt disable 318 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Library Example CHAPTER 6 Libraries The following code is code for the Manchester receiver it shows how to use the Manchester Library for receiving data LCD module connections sbit LCD RS at PORTD B2 sbit LCD EN at PORTD B3 sbit LCD D4 at PORTD B4 sbit LCD D5 at PORTD B5 sbit LCD D6 at PORTD B6 sbit LCD D7 at PORTD B7 sbit LCD RS Direction at DDRD B2 sbit LCD EN Direction at DDRD B3 sbit LCD D4 Direction at DDRD B4 sbit LCD D5 Direction at DDRD B5 sbit LCD D6 Direction at DDRD B6 sbit LCD D7 Direction at DDRD B7 End LCD module connections Manchester module connections sfr sbit MANRXPIN at PINB B0 sfr sbit MANRXPIN Direction at DDRB B0 sfr sbit MANTXPIN at PORTB B1 sfr sbit MANTXPIN Direction at DDRB B1 End Manchester module connections char error ErrorCount temp void main ErrorCount 0 anchester Stop Led_Init Initialize LCD Lcd Cmd LCD CLEAR Clear LCD display Man Receive Init Initialize Receiver while 1 Endless loop Lcd Cmd LCD
446. rview of RAM and ROM usage in the form of histogram RAM Memory Rx Memory Space Displays Rx memory space usage in form of histogram MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 53 CHAPTER 2 Environment mikroC PRO for AVR Data Memory Space Displays Data memory space usage in form of histogram Special Function Registers Summarizes all Special Function Registers and their addresses a EERE 54 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment General Purpose Registers Summarizes all General Purpose Registers and their addresses Also displays sym bolic names of variables and their addresses DefDevicehd ress _ _Lib_ PIGled_DefDeviceAddress spfontw SPlGlcd spfonH Lib SPlGlcd spiontH spilontDet _LspitontDef SpLRd LSpLRd _ cor FARG_SPI_Gled_H_Line 3 SPLGld H ne loc L0 _ y pos FARG SPI Gled H Line 2 FARG SPI Glcd H Line 0 axend FARG SPI Glcd Linee dala ou FARG_SP 1_Read O FARG SPI Glcd V Line 3 2 SPI Gled V Line loc L0 ix pos FARG SPI Glcd Line 2 FARG SPI Glcd V Line 0 FARG SPI V Lines ho SPI ROM Memory ROM Memory Usage Disp
447. s If it succeeds it sends the No of start sec tor over UART unsigned long size size Cf Fat Get Swap File 1000 mikroE txt 0x20 if size UART Write OxAA UART Write Lo size UART Write Hi size UART Write Higher size UART Write Highest size UART Write OxAA 268 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Library Example The following example is a simple demonstration of CF Compact Flash Library which shows how to use CF card data accessing routines include built _in h set compact flash pinout sfr char Cf Data Port at PORTD sfr char Cf Data Port Direction at DDRD sfr CF RDY at PINB B7 sfr CF WE at PORTB B6 sfr CF OE at FORTB B5 sfr CF 1 at PINB B4 sfr CF 1 at PORTB B3 sfr CF A2 at PORTB B2 sfr CF A1 at PORTB B1 sfr CF AO at PORTB BO sfr CF RDY direction at DDRB B7 sfr CF WE direction at DDRB B6 sfr CF OE direction at DDRB B5 sfr CF CD1 direction at DDRB B4 sfr 1 direction at DDRB B3 sfr CF A2 direction at DDRB B2 sfr CF Al direction at DDRB B1 sfr CF A0 direction at DDRB BO end of cf pinout char fat txt 20 FAT16 not found file contents 50 XX CF FAT16 library by Anton Rieckertn char filename 14 MIKROOOxTXT File names unsigned short tmp caracter loop loop2 unsigned long i size char Bu
448. s Too many characters Assembler instruction 5 was not found project name must be specified Unknown command line Option File extension missing s Bad FO argument 5 Preprocessor exited with error code s Bad absolute address 55 Recursion or cross calling of 55 no files specified Device parameter missing for example PATMEGA Invalid parameter string Project name must be set Specifier needed Ss not found 96s Index out of bounds Array dimension must be greater than 0 Const expression expected Integer const expected Recursion in definition Array corrupted Arguments cannot be of void type Arguments cannot have explicit memory specificator Bad storage class Pointer to function required Function required Illegal pointer conversion to double Integer type needed Members cannot have memory specifier Members cannot be of bit or sbit type Too many initializers Too many initializers of subaggregate Already used 55 Illegal expression with void Address must be greater than 0 Address must be greater than 0 s Identifier redefined User abort Exp must be greater than 0 Invalid declarator expected or identifier typdef name redefined 5s Declarator error Specifer qualifier list expected 88 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PR
449. s not our IP nor IP broadcast address 3 received IP packet was not IPv4 4 received packet was of type unknown to the library This is MAC module routine It processes next received packet if such exists Packets are processed in the following manner ARP amp ICMP requests are upon TCP request the SPI Description processing upon UDP request the SP processing replied automatically Ethernet UserTCP function is called for further Ethernet UserUDP function is called for further Note SPI Ethernet doPacket must be called as often as possible in user s code Ethernet module has to be initialized See SPI Ethernet Init 1 438 MIKROELEKTRONIKA SOFTWARE Ethernet doPacket process received packets AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI_Ethernet_putByte Prototype void SPI Ethernet putByte unsigned char v This is MAC module routine It stores one byte to address pointed by the current ENC28J60 write pointer EWRPT Description Parameters v value to store Ethernet module has to be initialized See SPI Ethernet Init char data SPI Ethernet putByte data put an byte into ENC28J60 buffer SPI Ethernet putBytes Prototype void SPI Ethernet putBytes unsigned char ptr unsigned char n This is MAC module routine It stores requested number of bytes into zNc28760 RAM starting from current
450. s are in the lower byte of the result Description Parameters ModuleAddress Port Expander hardware address see schematic at the bottom of this page Port Expander must be initialized See Expander_Init Port Expander s PortA and PortB should be configured as inputs See Expander_Set_DirectionPortA Expander_Set_DirectionPortB and Expander_Set_DirectionPortAB routines Read a byte from Port Expander s PORTA and PORTB unsigned int read data Expander Set DirectionPortAB 0 OxFFFF set expander s porta and portb to be input read data Expander Read PortAB 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 357 CHAPTER 6 Libraries mikroC PRO for AVR Expander_Write_PortA Prototype void Expander Write PortA char ModuleAddress char Data The function writes byte to Port Expander s PortA Parameters Description ModuleAddress Port Expander hardware address see schematic at the bottom of this page Data data to be written Port Expander must be initialized See Expander Init Port Expander s PortA should be configured as output See Expander_Set_DirectionPortA and Expander_Set_DirectionPortAB routines Write a byte to Port Expander s PORTA Expander Set DirectionPortA 0 0x00 set expander s porta to be output Expander Write PortA 0 OxAA 358 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO f
451. s from this evaluation are completed before the next statement starts executing Most of expression statements are assignment state ments or function calls A null statement is a special case consisting of a single semicolon The null statement does nothing and therefore is useful in situations where the mikroC PRO for AVR syntax expects a statement but the program does not need one For exam ple a null statement is commonly used in empty loops for body of this loop is a null statement 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 209 CHAPTER 5 Language Reference mikroC PRO for AVR 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 is false state ment2 executes The expression must evaluate to an integral value otherwise the condition is ill formed Parentheses around the expression are mandatory The else keyword is optional but no statements can come between if and else Nested If statements Nested if statements require additional attention A general rule is that the nested conditionals are parsed
452. s in the token sequence is 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 if the macro expands into something that looks like a preprocessing directive 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 so define MACRO MACRO won t expand indefinitely Here is an example Here are some simple macros define ERR MSG Out of range fdefine EVERLOOP for which we could use like this main EVERLOOP if error Lcd Out Cp ERR MSG break pes 220 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference 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 fendif The middle line is bypassed if BLOCK_SIZE is currently defined if
453. s not exist and no new file is created 1 if file already exists or file does not exist but a new file is created Assigns file for file operations read write delete All subsequent file operations will be applied over the assigned file Parameters filename name of the file that should be assigned for file operations The file name should be in DOS 8 3 file_name extension format The file name and extension will be automatically padded with spaces by the library if they have less than length required i e mikro tx gt mikro tx so the user does not have to take care of that The file name and extension are case insensitive The library will convert them to prop er case automatically so the user does not have to take care of that Also in order to keep backward compatibility with the first version of this library file names can be entered as UPPERCASE string of 11 bytes in length with no dot character between the file name and extension i e MIKROELETXT gt MIKROELE TXT In this case the last 3 characters of the string are considered to be file extension file cre attr file creation and attributs flags Each bit corresponds to the Description appropriate file attribut si Volume Label Subdirectory 6 0x40 Device internal use only never found on disk File creation flag If the file does not exist and this flag is set 7 0x80 a new file with specified name will
454. sambiguation Some ambiguous situations might arise when using escape sequences Here is an example Led_Out_Cp x091 0 Intro This is intended to be interpreted as x09 and 1 0 Intro However the mikroC PRO for AVR compiles it as the hexadecimal number x091 and literal string 0 Intro To avoid such problems we could rewrite the code in the following way Lcd Out 09 1 0 Intro For more information on the previous line refer to String Constants Ambiguities might also arise if an octal escape sequence is followed by a nonoctal digit For example the following constant UAN 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 PRO for AVR STRING CONSTANTS String constants also known as string literals are a special type of constants which store fixed sequences of characters A string literal is a sequence of any number of characters surrounded by double quotes This is a string The null string or empty string is written like A literal string is stored internally as a given sequence of characters plus a final null character A null string is stored as a single null character The characters inside the double quotes can include escape sequences This code for example NtV NameN NN tAddressVnNMn pr
455. sed in single quotes such as or n In the mikroC PRO for AVR single character constants are of the unsigned int type Multi character constants are referred to as string constants or string literals For more information refer to String Constants Escape Sequences A backslash character is used to introduce an escape sequence which allows a visual representation of certain nongraphic characters One of the most common escape constants is the newline character n A backslash is used with octal or hexadecimal numbers to represent an ASCII sym bol or control code corresponding to that value for example x3F for the ques tion mark Any value within legal range for data type char 0 to oxrr for the mikroC PRO for AVR can be used Larger numbers will generate the compiler error Out of range For example the octal number 777 is 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 PRO for AVR Language Reference Newline Linefeed Tab horizontal 7 Single quote Apostrophe t pe p pose _ Di
456. sest preceding the tif 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 if can be used and they can test whether an identifier is currently defined or not 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 is 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 is considered to be defined 226 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER mikroC PRO for AVR Libraries mikroC PRO for AVR provides a set of libraries which simplify the initialization and use of AVR compliant MCUs and their modules Use Library manager to include mikroC PRO for AVR Libraries in you project 227 CHAPTER 6 Libraries mikroC PRO for AVR Hardware AVR specific Libraries ADC Library CANSPI Library Compact Flash Library EEPROM Library Flash Memory Library Graphic LCD Library Keypad Library LCD Library Manchester Code Library Multi Media Card library OneWire Library Port Expander Library PS 2 Library PWM Library PWM 16 bit Library RS 48
457. sing 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 countbrz countcr etc but not countar counter etc Within a list the character is used to specify a range so that a z represents all characters between a and z inclusive If you want itself to be a member of a class put it at the start or end of the list or escape it with a backslash If you want you may place it at the start of list or escape it with a backslash Examples az matches z and Li j az j matches s z and a z matches a z and a z matches all twenty six small characters from to z n x0D matches any of 10 11 12 13 d t matches any digit or t a matches any char from Metacharacters Metacharacters are special characters which are the essence of regular expres sions There are different types of metacharacters described below 70 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 2 mikroC PRO for AVR Environment Metacharacters Line separators start of line end of line start of text 2 end of text any character in line Exam
458. sion field is where you specify a minimum number of dig its 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 digits in the argument is less than the precision field the output value is padded on the left with zeros The precision field is where you specify a number of digits to the right of the decimal point The last digit is rounded The precision field is where you specify a number of digits to the right of the decimal point The last digit is rounded The precision field is where you specify a maximum number of significant digits in the output value The precision field has no effect on these field types The precision field is where you specify a maximum number of characters in the output value Excess characters are not output CHAPTER 6 mikroC PRO for AVR Libraries The optional characters 1 or L may immediately precede conversion type to respectively specify long versions of the integer types i u o x and x Description You must ensure that the argument type matches that of the format specification You can use type casts to ensure that the proper type is passed to sprintf sprintl Prototype sprintl char wh const char f Returns The function returns the number of characters actually written to destination string The same as sprintf except it doesn t support float type numbers s
459. sitive With shift left far left bits are discarded and new bits on the right are assigned zeroes Thus shifting unsigned operand to the left by n positions is equivalent to multiplying it by 2n if all discarded bits are zero This is also true for signed operands if all discarded bits are equal to a sign bit 000001 lt lt 5 equals 000040 0x3801 lt 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 n positions is equivalent to divid ing it by 21 OxFF56 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 0222222 amp 0555555 equals 000000 0222222 amp amp 0555555 equals 1 0x1234 equals OxEDCB 0 1234 equals 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 199 CHAPTER 5 Language Reference mikroC PRO for AVR LOGICAL OPERATORS Operands of logical operations are considered true or false that is non zero or zero Logical operators always return 1 or 0 Operands in a logical expression must be of scalar type Logical operators and associate from left to right Logical negation ope
460. splayTxtPanel T6963C SetGrPanel T6963C SetTxtPanel T6963C PanelFill T6963C GrFill T6963C TxtFill T6963C Cursor Height T6963C Graphics T6963C Text T6963C Cursor T6963C Cursor Blink 508 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries T6963C_Init void T6963C Init unsigned int width unsigned char height unsigned char fntW Nothing Initalizes the Graphic Lcd controller Prototype Parameters width Width of the GLCD panel height height of the GLCD panel ntw font width Display RAM organization The library cuts the RAM into panels a complete panel is one graphics panel followed by a text panel see schematic below schematic Description Global variables T6963C dataPort Data Port T6963C ctrlPort Control Port T6963C ctrlwr Write signal pin T6963C ctrlrd Read signal pin T6963C ctrlcd Command Data signal pin T6963C ctrlrst Reset signal pin MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 509 CHAPTER 6 Libraries mikroC PRO for AVR 6963 dataPort Direction Direction of Data Port 6963 ctrlPort Direction Direction of Control Port 6963 ctrlwr Direction Direction of Write signal pin 6963 ctrlrd Direction Direction of Read signal pin Requires 2 6963 ctrlcd Direction Direction of Command Data sign
461. ssed to this Lcd Custom Out Cp temp Lcd Custom Out Cp IntToStr temp Operator Operator 44 is used for token pasting Two tokens can be pasted merged together by placing 44 in between them plus optional whitespace on either side The pre processor removes whitespace and combining the separate tokens into new token This is commonly used for constructing identifiers For example see the definition of macro sPLICE for pasting two tokens into one identifier define SPLICE x y x y Now the call SPLICE cnt 2 Will expand to the identifier cnc 2 Note The mikroC PRO for AVR does not support the older nonportable method of token pasting using 1 r 224 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR 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 PRO for AVR 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 if elif else 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 if has a non
462. ssion ps gt m indirect access to member m identical to ps m is of the type and represents the member object m in s The expression ps m is convenient shorthand for ps m For example struct mystruct Ine ws char stx 21 double d 5 sptr amp s Sup v assign to the i member of mystruct s sptr gt 1 23 assign to the d member of mystruct s The expression s n is lvalue providing that s is lvalue and m is not an array type The expression sptr gt m is an lvalue unless is an array type 168 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference 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 Fus struct int i struct aa double Bp o3 assign 3 to the i member of B S aa j 2 assign 2 to the j member of A sptr gt 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 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
463. t 17 Find In Files 18 Go oss RATER BRAM n AC TERR RN em RU 18 Regular expressions 19 View Menu Options 20 Toolbats mnc Ve Re VEG VU AUR ee 21 File Toolbar 21 Edit Toolbar 22255520 pee Ie Res 21 Advanced Edit 22 Find Replace 22 Project Toolbar adit ein bide 23 Build Toolbar 23 Debugger x cce neta RP RR Ee Pee a ee E 24 styles Toolbar dnm Rs 25 Tools Toolbar otc dea hha de Pea bee OR HER pee 25 Project Menu Options 26 IV MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Table of Contents Run Menu 28 Tools Menu 30 Help Menu Options 31 Keyboard Shortcuts 2 2 2 2 te ug idea rr Rer 32 mikroc pro for 35 IDE QVervIe
464. t Initialize SPI module used with PortExpander SPI Rd Ptr SPI2 Read Pass pointer to SPI Read function of used SPI module SPI Lcd8 Config 0 Intialize Lcd in 8bit mode via SPI SPI Lcd8 Cmd LCD CLEAR Clear display SPI Lcd8 Cmd LCD CURSOR OFF Turn cursor off SPI Lcd8 Out 1 6 text Print text to Lcd 1st row 6th column SPI Ledge Ohr CP 7 Append SPI Lcd8 Out 2 1 mikroelektronika Print text to Lcd 2nd row ist column SPI Lcd8 Out 3 1 text For Lcd modules with more than two rows SPI Lcd8 Out 4 15 text For Lcd modules with more than two rows MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 481 CHAPTER 6 Libraries mikroC PRO for AVR HW Connection MCP23817 un 17 H 2 GPBO GPA7 Di 25 H 27 GPB1 GPA6 C D2 39 26 GPB2 GPAs D3 4H 25 RS m GPA4 5H 24 lt SPB gt D5 6H E23 E GPB5 GPA2 D 73 L 22 GPB6 GPA D7 85 21 GPB7 VCC 9 E 20 ITI ei 0 10 VDD INTA OSCILLATOR S E 19 Q 1 pB 1 114 VSS NE 18 0 cs RESET gt PB 7 125 17 PB 13 SCA AL 46 T 5 15 o so Ao vec p Contrast Adjustment
465. t if amp 1 lt lt i str lt td bgcolor red gt ON else strt lt td bgcolor cccccc gt OFF Strte lt td gt lt trS document write str lt script gt o font family MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 445 CHAPTER 6 Libraries mikroC PRO for AVR 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 tr gt lt th colspan 3 gt PORTD lt th gt lt tr gt script Var stris str for 1 0 1 lt 8 1 strt lt tr gt lt td bgcolor yellow gt LED it lt td if PORTD 1 lt lt i strt t lt td bgcolor red gt ON else strt lt td bgcolor cccccc gt OFE strt lt td gt lt td lt a href t tit gt Toggle lt a gt lt td gt lt tr gt document write str lt script gt lt table gt lt td gt lt tr gt lt table gt This is HTTP request lt script gt document write REQ lt script gt lt BODY gt lt HTML gt BRK KKK kk kk Kk ko ko kkk kkk kk ke ke ke ke ke ke e e RAM variables K unsigned char myMacAddr 6 0x00 0x14 0xA5 0x76 0x19 0x3f my address unsigned char myIpAddr 4 1192 168 205 60 A my IP address unsigned char getRequest 15 4 HTTP request buffer unsigned char dyna 29 Ei buffer for dynamic response unsigned long httpCounter 0 counter of
466. t return len return to the library with the number of bytes to transmit this function is called by the library the user accesses to the UDP request by successive calls to Spi Ethernet _getByte the user puts data in the transmit buffer by successive calls to Spi Ethernet putByte the function must return the length in bytes of the UDP reply or 0 if nothing to transmit if you don t need to reply to UDP requests just define this function with a return 0 as single statement W MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 449 CHAPTER 6 Libraries mikroC PRO for AVR unsigned int SPI Ethernet UserUDP unsigned char remoteHost unsigned int remotePort unsigned int destPort unsigned int reqLength unsigned int len my reply length reply is made of the remote host IP address in human read able format ByteToStr remoteHost 0 dyna 4 first IP address byte 3 ByteToStr remoteHost 1 dyna 4 second dyna 7 ByteToStr remoteHost 2 dyna 8 third dyna 11 ByteToStr remoteHost 3 dyna 12 fourth dyna 15 add separator then remote host port number WordToStr remotePort dyna 16 dyna 21 WordToStr destPort dyna 22 27 28 0 the total length of the request is the length of the dynamic string pl
467. t Append pel The procedure moves the file pointer to the end of the assigned file so that data Description can be appended to the file The file must be assigned see Mmc Fat Assign Bampi paea O 330 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Mmc_Fat_Read Prototype Fat Read unsigned short bdata Procedure reads the byte at which the file pointer points to and stores data into Description parameter data The file pointer automatically increments with each call of Mmc_Fat_Read The file must be assigned see Mmc_Fat_Assign Also file pointer must tialized see Mmc_Fat_Reset Example ecrereeemmen O Mmc Fat Delete Deletes currently assigned file from MMC SD card MMC SD card and MMC library must be initialized for file operations See Fat Init The file must be previously assigned See Mmc Fat Assign delete current file Mmc Fat Delete Mmc Fat Write Prototype Fat Write char fdata unsigned data len Procedure writes a chunk of bytes fdata to the currently assigned file at the Deseription position of the file pointer The file must be assigned see Mmc_Fat_Assign Also file pointer must be ini see Mmc_Fat_Append Mmc_Fat_Rewrite Fat Write txt 255 Mmc Fat Write Hello world 255 Requires MIKROELEKTRONIKA SOFTWARE AND HARDWARE
468. t Init dees 384 PWM16bit_Change Duty 386 PWMTObIE Start csse uo Cae ee a Re 387 16 387 Library 388 HW Connection 2 2 1 1 4 4 2 389 5 485 106 ae ada tats S adie hata ae ach ae 390 External dependencies of RS 485 390 Library RoutineS 391 RS485Master_Init 391 RS485Master Receive 392 RS485Master Send 393 54855 _ 394 RS485Slave Receive 395 RS485Slave Send 396 Library 396 XX MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Table of Contents AW Connection i baee nee dente pease P EE Sd 400 Message format and CRC calculations 401 Software IC 402 External dependecies of Soft I2C 402 Library
469. t routine display graphic panel 1 T6963C DisplayGrPanel 1 T6963C DisplayTxtPanel Prototype void T6963C DisplayTxtPanel char n Display selected text panel Description Parameters n text panel number Valid values 0 and 1 Toshiba GLCD module needs to be initialized See the T6963C Init routine display text panel 1 T6963C DisplayTxtPanel 1 520 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries T6963C_SetGrPanel Prototype void 16963C_SetGrPanel char n Nothing Compute start address for selected graphic panel and set appropriate internal pointers All subsequent graphic operations will be preformed at this graphic panel Description Parameters n graphic panel number Valid values 0 and 1 Toshiba GLCD module needs to be initialized See the 6963 routine Example set graphic panel 1 as current graphic panel T6963C SetGrPanel 1 T6963C SetTxtPanel Prototype void T6963C SetTxtPanel char n Compute start address for selected text panel and set appropriate internal point ers All subsequent text operations will be preformed at this text panel Description Parameters n text panel number Valid values 0 and 1 Toshiba GLCD module needs to be initialized See the T6963C_Init routine set text panel 1 as current text panel T6963C SetTxtPanel 1 MIKROELEKTRONIKA SOFTWAR
470. tate flag void main Button Pin Direction 0 Set pin as input DDRC Configure PORTC as output PORTC Initial PORTC value oldstate do if Button 1 1 Detect logical one oldstate 1 Update flag if oldstate amp amp Button 1 0 Detect one to zero transition PORTC PORTC Invert PORTC oldstate 0 Update flag while 1 Endless loop 560 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries CONVERSIONS LIBRARY The mikroC PRO for AVR Conversions Library provides routines for numerals to strings and BCD decimal conversions Library Routines You can get text representation of numerical value by passing it to one of the follow ing routines ByteToStr ShortToStr WordToStr IntToStr LongToStr LongWordToStr FloatToStr The following functions convert decimal values to BCD and vice versa Dec2Bcd 20 16 Dec2Bcd16 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 561 CHAPTER 6 Libraries ByteToStr Prototype void ByteToStr unsigned short input char output Converts input byte to a string The output string has fixed width of 4 characters including null character at the end string termination The output string is right justified and remaining positions on the left if any are filled with blanks Description Requires ShortToStr Prototype
471. te All Software Library functions are blocking call functions they are waiting for 1 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 variable must be defined in all projects using RS 485 Library Description extern sbit Sbit 2 i Soft I2C Scl Output ft I2 1 Soft IC Clock output line 120 Scl Soft Scl Output at PORTC B0 extern sbit shat Soft I2C Data output line 5 2 Sda Output Soft I2C Sda Output at PORTC B1 extern sbit iin 2 i i ft I2C Scl Input at Soft Scl Input Softl4C Clock input line 5915 504 Input UCET e PINC B0 sbit extern sbit 2 i i ft 12 Input at Soft I2C Sda Input 9Oftl C Data input line 2 nput a extern sbit 2 sbit Soft I2C Scl Pin Dire Direction of the Soft IC 5256 156 sci pin Dire ction Clock pin ction at DDRC B0 extern sbit 2 sbit Soft I2C Sda Pin Dire Direction of the Soft IC 5256 2 saa pin Dire clon Data pin ction at DDRC B0 402 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR Library Routines CHAPTER 6 Libraries Soft I2C Init Soft 2 Start Soft I2C Read Soft I2C Write Soft 2 Stop Soft I2C Break Soft I2C Init Prototype void Soft
472. te Swap File UART1 Write e else I Write Str fat txt Test termination PORTC MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 345 CHAPTER 6 Libraries mikroC PRO for AVR HW Connection SPI MISO MMC CS SPI MOSI SPI SCK 2K2 2 E 5 3 3 6 SCK MMC SD 7 CARD VCC GND A VOUT 10uF i Back view MMC back view 346 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR 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 distances up to 300 meters small data transfer packages Each OneWire device has also a unique 64 bit registration number 8 bit device type 48 bit
473. tement 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 PRO for AVR might ignore it a b Evaluate b but discard value tta Side effect on a but discard value of Empty expression or a null statement MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 139 CHAPTER 5 Language Reference mikroC PRO for AVR Semicolons are sometimes used to create an empty statement for i 0 i For more information see the Statements Colon Use colon to indicate the labeled statement start x 0 goto start Labels are discussed in 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 int ptr 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 pointer as mul tiplication operator qj int ptr a b 3 14 For more information see the Pointers Equal Sign Equal sign s
474. tern Auto The auto modifer is used to define that a local variable has a local duration This is the default for local variables and is rarely used auto can not be used with globals See also Functions Register At the moment the modifier register technically has no special meaning The mikroC PRO for AVR compiler simply ignores requests for register allocation MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 181 CHAPTER 5 Language Reference mikroC PRO for AVR 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 function 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 is 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 is defined separate source code module Func tions declared with extern are visible throughout all source files in the program unless the function is redefined as static See Linkage fo
475. the source code 126 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference INTEGER CONSTANTS Integer constants can be decimal base 10 hexadecimal base 16 binary base 2 or octal base 8 In the absence of any overriding suffixes the data type of an integer constant is derived from its value Long and Unsigned Suffixes The suffix or1 attached to any constant forces that constant to be represented as a long Similarly the suffix u or u forces a constant to be unsigned Both L and u suffixes can be used with the same constant in any order or case ul Lu UL etc In the absence of any suffix U L or 1 a constant is assigned the smallest of the following types that can accommodate its value short unsigned short int unsigned int long int unsigned long int Otherwise If a constant has the 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 suffix its data type will be the first of the following that can accommodate its value long int unsigned long int If a constant has both and suffixes LU or ur its data type will be unsigned long int Decimal Decimal constants from 2147483648 to 4294967295 are allowed Constants exceeding these bounds will produce an Out of range error Decimal constants must n
476. the structure in memory can be retrieved by means of the operator sizeof lt is not necessary that the size of the structure is equal to the sum of its members sizes It is often greater due to certain limitations of memory storage 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 func2 returns pointer to structure A structure can be passed as an argument to a function in the following ways void funci mystruct si directly void func2 mystruct sptr via a pointer MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 167 CHAPTER 5 Language Reference mikroC PRO for AVR STRUCTURE MEMBER ACCESS Structure and union members are accessed using the following two selection oper ators 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 declared in s then the expression s m direct access to member m is of the type M and represents the member object n 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 is a pointer to s Then if m is a member iden tifier of the type declared in s the expre
477. theses these rules resolve a grouping of expres sions with operators of equal precedence Operators Associativity aa Eee a ee s amp sizeof 194 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR 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 7 mme 7 modulus operator returns the remainder of inte ger division cannot be used with floating points Unary Operators unary plus does not affect the operand 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 adds one before it evaluates decrement subtracts one from the value of the operand Postdecrement subtracts one from the value of the operand after it evaluates while pre decrement subtracts one before it evaluates Note Operator is context sensitive and can also represent the pointer reference operator Binary Arithmetic Operators Division of two integers returns
478. this value is not available on every MCU Please use Code Assistant to see if this value is available for the given MCU Sets prescaler value to 256 Sets prescaler value to 1024 Sets prescaler value to 1 on second PWM library if it exists in Library Manager Sets prescaler value to 8 on second PWM library if it exists in Library Manager Sets prescaler value to 32 on second PWM library if it exists in Library Manager This value is not available on every MCU Please use Code Assistant to see if this value is available for the given MCU Sets prescaler value to 64 on second PWM library if it exists in Library Manager Sets prescaler value to 128 on second PWM library if it exists in Library Manager This value is not available on every MCU Please use Code Assistant to see if this value is available for the given MCU Sets prescaler value to 256 on second PWM library if it exists in Library Manager Sets prescaler value to 1024 on second PWM library if it exists in Library Manager Selects the inverted PWM mode Selects the inverted PWM mode on second PWM library if it exists in Library Manager Selects the normal non inverted PWM mode Selects the normal non inverted PWM mode on second PWM library if it exists in Library Manager 373 CHAPTER 6 Libraries mikroC PRO for AVR Note Not all of the MCUs have both PWM and PWM1 library included Sometimes like its the case with ATmega8515 MCU
479. ting and for documenting your project Press the button bellow to generate HTML statistics and to open them in the default web browser View HTML statistics 58 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR CHAPTER 2 Environment MACRO EDITOR A macro is a series of keystrokes that have been recorded in the order performed A macro allows you to record a series of keystrokes and then playback or repeat the recorded keystrokes Macro3 The Macro offers the following commands Icon Description Starts recording keystrokes for later playback Stops capturing keystrokesthat was started when the Start Recordig command was selected Allows a macro that has been recorded to be replayed New macro Delete macro Related topics Advanced Code Editor Code Templates MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 59 CHAPTER 2 Environment mikroC PRO for AVR INTEGRATED TOOLS USART Terminal The mikroC PRO for AVR includes the USART communication terminal for RS232 communication You can launch it from the drop down menu Tools USART Termi nal or by clicking the USART Terminal Icon from Tools toolbar E Communication Echo Je 7 Append CR Send as typing 7 Send as number 60 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBE
480. tion Referencing declarations or just declarations simply make their identifiers and types known to the compiler Here is an overview Declaration is also a definition except if it declares a function without specifying its body it has the extern specifier and has initializator or body in 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 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 gt y x 178 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference Definition of variable i ape Following line is an error i is already defined ir 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 varl initl var2 init2 where v
481. tom Character 66 Sue 555 67 Code editor et ieee eee d 67 Tools 2 4222 dade wed dae ens eer ees RR ARR S 67 Output settings 222225229429 0 Phe Reed kde odds 68 Regular Expressions 69 Introduction 69 Simple matches 69 Escape sequences 69 Character classes neracia 4 RR LER Be aa wes 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 PRO for AVR Command Line Options 75 tutorials hile REX a Sade 76 cade C m Ron XR ed Ps A TR 76 ed idee bebe wade Ede e pae de 76 New Project Wizard 77 VI MIKROELEKTRONIKA SO
482. ton of the word would encompass functions variables symbolic constants user defined data types and labels Each value has an associated name and type also known as a data type The name is used to access the object and can be a simple identifier or complex expres sion that uniquely refers the object 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 attrib utes storage class and type sometimes referred to as data type The mikroC PRO for AVR compiler deduces these attributes from implicit or explicit declarations in the source code Usually only the type is explicitly specified and the storage class spec ifier assumes the automatic value auto Generally speaking an identifier cannot be legally used in a program before its dec laration point in the source code Legal exceptions to this rule known as forward ref erences are labels calls to undeclared functions and struct or union tags The range of objects that can be declared includes 142 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference Variables Functions Types Arrays of other types Structure union and enumeration tags Structure members Union members Enumeration constants St
483. truct the linker which functions can be called indirectly from the current function pragma funcall func name called func called func A corresponding pragma must be placed in the source module where the function func name is 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 unc is called in the code no mat ter whether any of them was called or not Note The pragma funcall directive can help the linker to optimize function frame allocation in the compiled stack MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 105 CHAPTER 3 Specifics mikroC PRO for AVR BUILT IN ROUTINES The mikroC PRO for AVR 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 n header file located the 1n1ciuae folder of the compil er into your project The Delay us and Delay ms routines are implemented as inline i e code is generated in the place of a call so the call doesn t count against the nested call limit The vdelay ms Delay Cyc and Get Fosc kHz are actual C routines Their sources can be found in Delays file located in the uses folder of the compiler Lo Hi Higher Highest Delay_us Delay ms Vdelay ms Delay Cyc Clock kHz C
484. tt Cf Write Sector sizet Buffer UART1 Write Ecce ere Main Uncomment the function s to test the desired operation s void main we will use PORTC to signal test end DDRC OxFF PORTC 0 set up USART for the file read UART1_Init 19200 Delay 100 use fati6 quick format instead of init routine if format ting is needed if Cf Fat Init Init the FAT library Test start UART1 Write s Create New File Create Multiple Files Open File Rewrite Open File Append Open File Read Delete File Test File Exist Create Swap File Test termination ART1 Write e Se else I Write Str fat txt Test termination PORTC OxO0F MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 273 CHAPTER 6 Libraries mikroC PRO for AVR HW Connection Compact Flash 10K 1 Pin diagram of CF memory card 274 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries EEPROM LIBRARY EEPROM data memory is available with a number of AVR family The mikroC PRO for AVR includes a library for comfortable work with MCU s internal EEPROM Note EEPROM Library functions implementation is MCU dependent
485. ture type or derived from it but addition al objects of this type cannot be declared elsewhere With tag typedef struct mystruct Mystruct Mystruct s ps arrs 10 same as struct mystruct s etc Without tag typedef struct Mystruct Mystruct s ps arrs 10 166 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference 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 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 b But and d not of the same type although their structure descriptions are identical Struct int mi m2 struct int mi m2 d Size of Structure The size of
486. u have entered edited in the current project First one is equal to the name of selected device for the project i e if ATmega16 is selected device then ATmega16 token will be defined as 1 so it can be used for conditional compilation ifdef 16 fendif The second one is FOSC value of frequency in Khz for which the project is built Third one is for identifying mikroC PRO for AVR compiler ifdef PRO FOR AVR fendif Fourth one is for identifying the build version For instance if a desired build version is 142 user should put this in his code if MIKROC PRO FOR AVR BUILD 142 fendif User can define custom project level defines MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 99 CHAPTER 3 mikroC PRO for AVR Specifics ACCESSING INDIVIDUAL BITS The mikroC PRO for AVR allows you to access individual bits of 8 bit variables It also supports sbit and bit data types Accessing Individual Bits Of Variables If you are familiar with a particular MCU you can access bits by name Clear bit 0 on PORTA PORTAO bit 0 Also you can simply use the direct member selector with a variable followed by one of identifiers Bo B1 B7 With B7 being the most significant bit Clear bit 0 on PORTA PORTA BO 0 There is no need of any special declarations This kind of selective access is an intrinsic feature of mikroC PRO for AVR and can be use
487. ual ity to null if 0 if pb 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 operators 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 type advances the pointer 50 bytes in memory In case of the voia type the size of a step is one byte For example int a 10 array a containing 10 elements of type int int pa amp a 0 pa is pointer to int pointing to a 0 pa 3 6 pa t3 is a pointer pointing to a 3 so af 3 now equals 6 patt pa now points to the next element of array a al ij There is no such element as one past the last element of course but the pointer is allowed to assume such value C guarantees that the result of addition is defined even when pointing to one element past array If points to the last array element
488. ucture is a derived type usually representing a user defined collection of named members or components These members can be of any type either fundamental or derived with some restrictions to be discussed later in any sequence In addi tion a structure member can be a bit field Unlike arrays structures are considered to be single objects The mikroC PRO for AVR structure type lets you handle complex data structures almost as easily as sin gle variables Note the mikroC PRO for AVR does not support anonymous structures ANSI diver gence 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 mystruct s illegal struct mystruct mystruct ps OK Also a structure can contain previously defined structure types when declaring an 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 k 201 0
489. uments int and char but can also have any number of additional arguments Example include lt stdarg h gt int addvararg char al va_list ap char temp va_start ap al while temp char al temp return al int res void main res addvararg 1 2 3 4 5 0 res addvararg 1 2 3 4 5 6 7 8 9 10 0 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference OPERATORS Operators are tokens that trigger some computation when applied to variables and other objects in an expression Arithmetic Operators Assignment Operators Bitwise Operators Logical Operators Reference Indirect Operators Relational Operators Structure Member Selectors Comma Operator Conditional Operator Array subscript operator Function call operator sizeof Operator Preprocessor Operators and MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 193 CHAPTER 5 Language Reference mikroC PRO for AVR 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 in the table the first occurrence is unary and the second binary Each category has an associativity rule left to right or right to left In the absence of paren
490. updat ed and properly used will perform substantially in accordance with the accompany ing documentation and Software media will be free from defects in materials and workmanship for a period of ninety 90 days from the date of receipt Any implied warranties on Software are limited to ninety 90 days mikroElektronika Associates and its suppliers entire liability and your exclusive remedy shall be at mikroElektronika Associates option either a return of the price paid or b repair or replacement of Software that does not meet mikroElektronika Associates Limited Warranty and which is returned to mikroElektronika Associates with a copy of your receipt DO NOT RETURN ANY PRODUCT UNTIL YOU HAVE CALLED MIKROELEKTRONIKAASSOCIATES FIRST AND OBTAINED A RETURN AUTHORIZATION NUMBER This Limited Warranty is void if failure of Software has resulted from an accident abuse or misapplication Any replacement of Software will be warranted for the rest of the original warranty period or thirty 30 days whichever is longer TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW MIKROELEKTRONIKA ASSOCIATES AND ITS SUPPLIERS DISCLAIM ALL OTHER WARRANTIES AND CONDITIONS EITHER EXPRESSED OR IMPLIED INCLUDED BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE TITLE AND NON INFRINGEMENT WITH REGARD TO SOFTWARE AND THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES IN NO EVENT SHALL MIKROELEKTRO
491. urrent duty DDRB B3 1 Set PORTB pin 3 as output pin for the PWM according to datasheet DDRD B7 1 Set PORTD pin 7 as output pin for the PWM according to datasheet PWM Init PWM FAST MODI Fl n PRESCALER 8 PWM NON INV Fl RTED PWM1 Init 1 FAST MODE PRESCALER 8 PWM1 NON INVERTED T2 do if PINB BO Detect if PORTB pin 0 is pressed Delay ms 40 Small delay to avoid deboucing effect current dutyt Increment duty ratio PWM Set Duty current duty Set incremented duty else if 1 Detect if PORTB 1 is pressed Delay ms 40 Small delay to avoid deboucing effect current duty Decrement duty ratio PWM Set Duty current duty Set decremented duty ratio else if PINC BO Detect if PORTC pin 0 is pressed Delay ms 40 Small delay to avoid deboucing effect current dutyl t Increment duty ratio PWM1 Set Duty current dutyl Set incremented duty 380 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries else if PINC B1 Detect if PORTC pin 1 is pressed Delay ms 40 Small delay to avoid deboucing effect current dutyl Decrement duty ratio PWM1 Set Duty current dutyl Set decremented duty ratio while 1 Endless loop HW Connection OSCILLATOR
492. us the text of the request len 28 reqLength puts the dynamic string into the transmit buffer SPI_Ethernet_putBytes dyna 28 then puts the request string converted into upper char into the transmit buffer while reqLength SPI Ethernet putByte toupper SPI Ethernet getByte return len back to the library with the length of the UDP reply main entry 0 450 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries void main set PORTC as input DDRC 0 set PORTD as output DDRD OxFF starts ENC28J60 with reset bit on PORTB B4 CS bit on PORTB B5 my MAC amp IP address full duplex X SPI1 Init Advanced SPI MASTER SPI DIV2 SPI CLK LO LEADING Spi Rd Ptr SPI1 Read pass pointer to SPI Read function of used SPI module SPI Ethernet Init myMacAddr myIpAddr Spi Ethernet FULLDU PLEX full duplex CRC MAC Unicast MAC Broadcast filtering while 1 do forever if necessary test the return value to get error code E SPI Ethernet doPacket process incoming Ethernet packets add your stuff here if needed Spi Ethernet doPacket must be called as often as possible otherwise packets could be lost MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 451 CHAPTER 6 Libraries mikroC PRO for AV
493. variables Related topics Bit fields Predefined globals and constants MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 101 CHAPTER 3 Specifics mikroC PRO for AVR INTERRUPTS AVR derivates acknowledges an interrupt request by executing a hardware gener ated CALL to the appropriate servicing routine ISRs ISRs are organized in IVT ISR is defined as a standard function but with the org directive afterwards which con nects the function with specific interrupt vector For example org 0 000 is IVT address of Timer Counter 2 Overflow interrupt source of the 16 For more information on interrupts and IVT refer to the specific data sheet Function Calls from Interrupt Calling functions from within the interrupt routine is allowed The compiler takes care about the registers being used both in interrupt and in main thread and performs smart context switching between them two saving only the registers that have been used in both threads It is not recommended to use function call from interrupt In case of doing that take care of stack depth Interrupt routine void Interrupt org 0x16 RS485Master Receive dat Most of the MCUs can access interrupt service routines directly but some can not reach interrupt service routines if they are allocated on addresses greater than 2K from the IVT In this case compiler automatically creates Goto table in order to jump to such interrupt service
494. ve different level of protection since they have different sets of Lock bits Depending on the settings made in compiler program memory may also used to store a constant variables The AVR executes programs stored in program memory only code memory type specifier is used to refer to program memory Program Memory MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 115 CHAPTER 4 AVR Specifics mikroC PRO for AVR Data Memory Data memory consists of Rx space Memory Extended I O Memory MCU dependent Internal SRAM Rx space consists of 32 general purpose working 8 bit registers RO R31 These registers have the shortest fastest access time which allows single cycle Arith metic Logic Unit ALU operation I O Memory space contains addresses for CPU peripheral function such as Control registers SPI and other I O functions Due to the complexity some AVR microcontrollers with more peripherals have Extended I O memory which occupies part of the internal SRAM Extended memory is MCU dependent Storing data in I O and Extended I O memory is handled by the compiler only Users can not use this memory space for storing their data Internal SRAM Data Memory is used for temporarily storing and keeping interme diate results and variables static link and dynamic link There are four memory type specifiers that can be used to refer to the data memo ry rx data io and sfr AVR memory
495. void main PORTB 0 clear PORTB PORTC 0 clear PORTC DDRB OxFF set PORTB as output DDRC OxFF set PORTB as output 398 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Pass pointers to UART functions of used UART module UART Wr Ptr UART1 Write UART Rd Ptr UART1 Read UART Ptr UARTI1 Data Ready UART TX Idle UART1 TX Idle UART1 Init 9600 initialize UART1 module Delay ms 100 RS485Slave Init 160 Intialize MCU as Slave address 160 dat 4 0 ensure that message received flag is 0 dat 5 0 ensure that message received flag is 0 dat 6 0 ensure that error flag is 0 SREG I 1 enable global interrupt RXCIE 1 enable interrupt on usart receive while 1 if dat 5 1 if an error detected signal it by PORTC dat 5 77 setting PORTC dat 5 0 if dat 4 upon completed valid message receive dat 4 0 data 4 is set to OxFF j dat 3 for i 1 i lt 3 i show data on PORTB PORTB dat i 1 dat 0 dat 0 1 increment received dat 0 Delay ms 1 RS485Slave Send dat 1 send it back to Master MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 399 CHAPTER 6 Libraries mikroC PRO for AVR HW Connection Shielded pair no longer than 300m
496. when mu holds char Union Member Access Union members can be accessed with the structure member selectors and gt be careful when doing this 170 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 5 mikroC PRO for AVR Language Reference Referring to declarations from th xample 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 171 CHAPTER 5 Language Reference mikroC PRO for AVR 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 PRO for AVR s intrinsic ability for individual
497. 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 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 9 CHAPTER 1 Introduction mikroC PRO for AVR 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 PRO for AVR at the time of activation Notes The license key is valid until you format your hard disk In case you need to format the hard disk you should request a new activation key Please keep the activation program in a safe place Every time you upgrade the compiler you should start this program again in order to reactivate the license 10 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD mikroC PRO for AVR USER MANUAL CHAPTER 2 mikroC PRO for AVR Environment The mikroC PRO for AVR is an user friendly and intuitive environment CHAPTER 2 Environment mikroC PRO for AVR IDE OVERVIEW The mikroC PRO for AVR is an user friendly and intuitive environment
498. wing 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 always return it as 4 switch i case 1 itt 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 211 CHAPTER 5 Language Reference mikroC PRO for AVR 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 PRO for AVR 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
499. with no dot character between file name and extension i e MIKROELETXT gt MIKROELE TXT In this case last 3 charac ters of the string are considered to be file extension file cre attr file creation and attributs flags Each bit corresponds to appropriate file attribut mak Been 0 po oor 6 0x40 Device internal use only never found on disk File creation flag If the file does not exist and this flag is set a new file with specified name will be created Note Long File Names LFN are not supported MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 329 CHAPTER 6 Libraries mikroC PRO for AVR MMC SD card and MMC library must be initialized for file operations See Create file with archive attribut if it does not already exists Fat Assign MIKROELE TXT 0OxA0 Mmc_Fat_Reset Prototype void Mmc Fat Reset unsigned long size Procedure resets the file pointer moves it to the start of the file of the assigned file so that the file can be read Description Parameter size stores the size of the assigned file in bytes The file must be assigned see Mmc_Fat_Assign Example Mmc_Fat_Rewrite Nothing ar Procedure resets the file pointer and clears the assigned file so that new data Description can be written into the file The file must be assigned see Mmc Fat Assign Mmc Fa
500. would be m 411 0 If you don t initialize the array in the declaration you can omit the first dimension of multi dimensional array In that case array is located elsewhere e g in another file This is a commonly used technique when passing arrays as function parameters int al 31121141 3 dimensional array of size 3x2x4 void func int n 2 4 we can omit first dimension n 2 1 3 increment the last element void main rune a You can initialize a multi dimensional array with an appropriate set of values within braces For example int a 3 2 111 2 2 6 3 7 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 157 CHAPTER 5 Language Reference mikroC PRO for AVR POINTERS Pointers are special objects for holding or pointing to memory addresses In the mikroC PRO for AVR 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 in a code segment where that function s executable code is stored that is the address to whi
501. written Stop issue TWI stop signal Delay 100ms TWI Start issue TWI start signal TWI Write 0xA2 send byte via TWI device address W TWI Write 2 send byte data address TWI Start issue TWI signal repeated start TWI Write 0xA3 send byte device address R PORTA TWI Read 0u read data NO acknowledge Stop issue TWI stop signal HW Connection VCC VCC v NC SCL GND SDA i 24C02 LEE 5 RJ OSCILLATOR 10K 10K Os z zd 9 1 IT 2 o Interfacing 24c02 to AVR via TWI MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 533 CHAPTER 6 Libraries mikroC PRO for AVR UART LIBRARY UART hardware module is available with a number of AVR MCUs mikroC PRO for AVR UART Library provides comfortable work with the Asynchronous full duplex mode You can easily communicate with other devices via RS 232 protocol for example with PC see the figure at the end of the topic RS 232 HW connection You need a AVR MCU with hardware integrated UART for example ATmega16 Then simply use the functions listed below Library Routines UARTx Init UARTx Init Advanced UARTx Data Ready UARTx Read UARTx Read Text UARTx Write UARTx
502. xpanderCS Direction at DDRB B1 End Port Expander module connections Pass pointer to SPI Read function of used SPI module SPI Rd Ptr SPI1 Read Initialize SPI module SPI1_ Init Advanced SPI MASTER SPI FCY DIV32 SPI CLK HI TRAIL ING SPI T6963C Config 240 486 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries SPI T6963C WriteData Prototype SPI T6963C WriteData unsigned char Ddata Writes data to T6963C controller via SPI interface Description Parameters Ddata data to be written Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Example SPI_T6963C_WriteCommand Prototype void SPI T6963C WriteCommand unsigned char Ddata Writes command to T6963C controller via SPI interface Description Parameters Ddata command to be written Toshiba Glcd module needs to be initialized See SPI T6963C Config routine P T6963C WriteCommand SPI T6963C CURSOR POINTE SPI T6963C SetPtr Prototype void SPI T6963C SetPtr unsigned int p unsigned char c Sets the memory pointer p for command c m Parameters Description p address where command should be written c command to be written Requires SToshiba Glcd module needs to be initialized See SPI T6963C Config routine SPI T6963C SetPtr T6963C grHomeAddr start T6963C ADDRESS POINT ER SET
503. xternal dependencies are the same as Port Expander Library external dependen cies Library Routines Basic routines SPI Init SPI Glcd Set Side SPI Glcd Set Page SPI Glcd Set X SPI Glcd Read Data SPI Glcd Write Data Advanced routines SPI Fill SPI Glcd Dot SPI Line SPI Glcd V Line SPI H Line SPI Glcd Rectangle SPI Glcd Box SPI Glcd Circle SPI Glcd Set Font SPI Glcd Write Char SPI Glcd Write Text SPI Glcd Image MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 453 CHAPTER 6 Libraries mikroC PRO for AVR SPI Glcd Init Prototype void SPI Glcd Init char DeviceAddress Nothing Initializes the Glcd modu TA Parameters Description le via SPI interface DeviceAddress SPI expander hardware address see schematic at the bottom of this page Chip Select line Reset line Direction Direction of the Chip Select pin Direction Direction of the Reset pin Global variables SPExpanderCs SPExpanderRS SPExpanderCS Requires SPExpanderRS1 must be defined before using this function The SPI module needs to be initialized See SPI Init and SPI Init Advanced routines ule connections at PORTB B0 at PORTB B1 Direction at DDRB B0 irection at DDRB B1 module connections Library uses SPI1 module SPI1 Init Advanced SPI MASTER SPI FCY DIV2 SPI CLK HI TRAIL
504. y 1 if data is received UART1 Read Text output delim 10 reads text until delim is found Write Text output sends back text 538 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries UARTx_Write The function transmits a byte via the UART module Description Parameters data data to be sent UART HW module must be initialized and communication established before using this function See UARTx Init unsigned char data 0 1 UART1 Write data UARTx Write Text Sends text parameter UART text via UART Text should be zero terminated Requires UART HW module must be initialized and communication established before q using this function See UARTx Init Read text until the sequence OK is received and send back what s been received UART1 Init 4800 initialize UART module Delay ms 100 while 1 if UART1 Data Ready 1 if data is received UART1 Read Text output delim 10 reads text until delim is found Write Text output sends back text MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 539 CHAPTER 6 Libraries mikroC PRO for AVR Library Example The example demonstrates a simple data exchange via UART When AVR MCU receives data it immediately sends it back If AVR is connected to the PC see the figure below you can test the exampl
505. y Routines Mmc Init Mmc Read Sector Mmc Write Sector Mmc Read Cid Mmc Read Csd Routines for file handling Mmc Fat Init Mmc Fat QuickFormat Mmc Fat Assign Mmc Fat Reset Mmc Fat Read Mmc Fat Rewrite Mmc Fat Append Mmc Fat Delete Mmc Fat Write Mmc Fat Set File Date Mmc Fat Get File Date Mmc Fat Get File Size Mmc Fat Get Swap File 324 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries Mmc_Init Prototype unsigned char Mmc Init 1 if MMC SD card was detected and successfully initialized 0 otherwise Initializes hardware SPI communication The function returns 1 if MMC card is Description present and successfully initialized otherwise returns 0 Mmc_Init needs to be called before using other functions of this library Global variables Chip Select Chip Select line Mmc Chip Select Direction Direction of the Chip Select pin must be defined before using this function MMC module connections sfr sbit Mmc Chip Select at PORTG B1 sfr sbit Mmc Chip Select Direction at DDRG B1 MMC module connections SPI1 Init Advanced SPI MASTER SPI FCY DIV2 SPI LO Ll ING Spi Rd Ptr 5 1 Read error Mmc Init Init with CS line at PORTB B2 Mmc Read Sector Prototype unsigned char Mmc Read Sector unsigned long sector char dbuff Returns Returns 0 if re
506. y0 int xl int yl unsigned char pcolor Prototype Draws a line from x0 yO to x1 y1 Parameters x0 X coordinate of the line start y0 y coordinate of the line end x1 X coordinate of the line start y1 y coordinate of the line end pcolor color parameter Valid values SPI 6963 BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine ae _T6963C Line 0 0 239 T6963C WHITE SPI T6963C Rectangle Description void SPI T6963C Rectangle int x0 int y0 int xl int yl unsigned char pcolor Draws a rectangle on Glcd Prototype Parameters x0 X coordinate of the upper left rectangle corner y0 y coordinate of the upper left rectangle corner x1 X coordinate of the lower right rectangle corner y1 y coordinate of the lower right rectangle corner pcolor color parameter Valid values SPI 6963 BLACK and SPI T6963C WHITE Toshiba Glcd module needs to be initialized See SPI T6963C Config routine Emm et Description MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD 491 CHAPTER 6 Libraries mikroC PRO for AVR SPI_T6963C_Box void SPI T6963C Box int x0 int y0 int x1 int yl unsigned char pcolor Draws a box on the Glcd Prototype Parameters x0 X coordinate of the upper left box corner y0 y coordinate of the upper left box corner x1 X coordinate of the
507. ype double atof char s 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 Description 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 550 MIKROELEKTRONIKA SOFTWARE AND HARDWARE SOLUTIONS FOR EMBEDDED WORLD CHAPTER 6 mikroC PRO for AVR Libraries atoi Prototype atoi char s Function converts the input string s into an integer value and returns the value The input string s should consist exclusively of decimal digits with an optional Description 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 atol Prototype long atol char s 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 Description optional whitespace and a sign at the beginning The string will be processed one character at a time until the function reaches a character which it doesn t recognize including a null character div Prototype div t div int number int Function computes the result of division of the numerator
508. zero value the line group immediately following the if directive is retained the translation unit The syntax is if constant expression 1 section 1 elif constant expression 2 section 2 gt felif constant expression n section n felse final section fendif Each i f directive in a source file must be matched by a closing endif directive Any number of e1if directives can appear between if and endif directives but at most one else directive is allowed The e1se 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 following each if or 4e1i f 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 220 CHAPTER 5 Language Reference mikroC PRO for AVR If all occurrences of constant expression are false or if e1i f directives appear the preprocessor selects the text block after the else clause If the telse clause is 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 tendi directive belongs to the clo
Download Pdf Manuals
Related Search
Related Contents
DSC880DW クイックスタートガイド(2.5MB) α One POINT Five カタログ (PDF 2.56MB) Titel KIM-Handbuch.indd user`s manual water kettle P2000/P2000LEのシステム構成 Correzione urgente relativa a dispositivo medico "取扱説明書" GE ASD06* Air Conditioner User Manual Lux Products TX500 (discontinued) Instruction Manual BENDIX 03-K-3 User's Manual Copyright © All rights reserved.
Failed to retrieve file