Home

1.1 Programming in C Language

image

Contents

1. Chapter 3 Using Real time OS MR30 3 1 Basics of Real time OS 3 2 Method for Using System Calls 3 3 Development Procedures Using MR30 3 4 Building MR30 into Program Using NC30 Appendices Appendix A Functional Comparison between NC30 and NC77 Appendix B NC30 Command Reference Appendix C Questions amp Answers Chapter 1 Introduction to C Language Programming in C Language Data Types Operators Control Statements Functions otorage Classes Arrays and Pointers Struct and Union Preprocess Commands 1 1 1 2 1 3 1 4 1 5 1 6 bel 1 8 1 9 This chapter explains for those who learn the C language for the first time the basics of the C language that are required when creating a built in program Introduction to C Language 1 1 1 Programming in C Language 1 1 Programming in C Language 1 1 1 Assembly Language and C Language As the scale of microcomputer based systems increased in recent years a program s productivity and maintainability became to attract the attention of the people concerned At the same time more and more programs have become to be developed in the C language instead of using the conventional assembly language The following explains the main features of the C language and describes how to write a program in the C language Features of the C language 1 An easily traceable program can be written The basics of st
2. A E Example 1 5 1 Finding Sum of Integers example for writing a function 1 6 Storage Classes L7 Arrays and P INIersS e mo ote Example 1 7 1 Finding Total Age of a Family cinswscsacesuresscaiuenss corenacsedacietassaseuesacchennmeannle clveriebesas Example 1 7 2 Finding Total Age of a Family lt 2 vcvcsvacieverentsianronsvtaneverech svar ey mika va abd ERR ROV ER vba cn Example 1 7 3 Switching Arithmetic Operations Using Table Jump eeeeseessssess 1 8 Struct and Union 1 9 Preprocess Commands Chapter 2 ROM ing Technology 2 1 Memory Mapping 2 2 Startup Program 2 3 Extended Functions for ROM ing Purposes eeeeeeeeee ee eeeeee rne nennen nnn Example 2 3 1 Defining SFR Area Using pragma ADDRESS cccccccccseeecceeeeeeeeeeeeeeeeeeeaees 2 4 Linkage with Assembly Language 11 eec Leeeee eese eene e enne nennen nnn nnne n nnn nnn 1 Example 2 4 1 Calling SubtrObllIi6 uu oar poer oinir teta ipa ttu pn dssneaetecensdechacieedeinetetscouss eaciecegsbeabee 1 Example 2 4 2 Calling a Subroutine by Table Jump ssseeeeeesseeeeeeennnnne 1 Example 2 4 3 A Little Different Way to Use Table Jump eere 1 2 5 Interrupt Processing
3. H 10 1 2 1 Constants Handleable in C Language ront nina pnr tenu pe n rRu ndn 10 2i 12 1 23 EID zur RETI SIENTE TTE E 14 pECNe iiir UU T 16 13 1 Operators Ol NGOO 16 1 3 2 Operators for Numeric Calculations cccccccsseeccceeceeeeeeeeeeeseeeeeeeeeeseeeeeeeesesseaeeeeeeessaeeeeees 17 1 33 Operators ior Processing B ITI T UU T 20 1 3 4 Operators for EXAMINING Condition eeeeesssssssssssssssseeeeneeee ennemis 29 1 5 0 Oher DSL 0 cere ee ee ee ence eee eee eee ee ne eee ee eee RUD LOEO eee 24 TSG Pronties oi 6 162 6 Cpe eee ene neon ER E omm 26 RE Neopets 27 UE eit tii las OEF 616 Cc Rm 27 1 4 2 Branching Processing Depending on Condition branch processing 28 1 4 3 Repetition of Same Processing repeat processing ccccsssssseeeeceeesseeeeeesseaseeeeeeeseseeeeess 32 144 S spending ajo 9 ETT T OE EO TO TET 35 To uidi e 37 Lod Dj ere HOS NG SU Ol OMIM GS spse NS E 37 1 9 2 Greating FUNCIONS eene oer ecratedcca E tes rim oc opor eet sans sale MmEd e MUI DM ER LAS MEC ES 38 1 5 3 Exchanging Data between Functions sscciceecem turi d orci tUm vensued To vas etse aeree Ee sit oascer Eni radi tese tures 40 tO Slorage Cla SSCS eem UU UT TM 41 1 6 1 Effective Range of Variables and Functi
4. Prototype declaration x2 24 2 2 oe 2 oA oe IR RA AR AC CR EA ACO ACR CA RCO ACR CR ORC ACR OR kokk kk void main void void key in void void key_out void Example of function header FUNC COMMENT sss esee t se oot se oe 2K 2 eot zb oe tok oko ake o heo E ok ke ok ok 2k ok ok 2k 2k ok 2k 2k ok be spoke ok ok ok 2k 2k ok ok 2k ok k k Function name main Functions used voidkey in void Input function voidkey out void Output function x FUNC COMMENT EN D scs ese ok o eol 2 a 2K 2 ok 2 ae ok 2 ok oe 2 EEEE ok 2k ok ok ole ak ok 2k ke ok ok ak ok ok ok ok ok ok ok ok 2k ok ok 2k ok ok kk void main void while 1 Endless loop key in Input processing key out Output processing j j Figure 1 1 5 Example for using comments Introduction to C Language 1 1 Programming in C Language Column Reserved words of NC30 The words listed in Table 1 1 2 are reserved for NC30 Therefore these words cannot be used in variable or function names Table 1 1 2 Reserved Words of NC30 if int switch typedef union unsigned void volatile while Introduction to C Language 1 1 2 Data Types 1 2 Data Types 1 2 1 Constants Handleable in C Language Four types of constants can be handled in the C language integer rea and character string This section explains the method of description and the precautions to be noted when using each of thes
5. 143 3 4 3 Writing Interrupt Handler lssseessssesssseeeenneeen nnnm nnns 147 3 4 4 Writing Cyclic and Alarm PIarcdleEkSuesccoieceniisatud une tnt EIE I Vu UERGE UXeUFPUCESLU TE n UEL UM ante drea tU 151 Appendices Appendix A Functional Comparison between NC30 and NC77 Appendix 3 Appendix B NC30 Command Reference 11 eeeeeeLeeeee eise enne enne n nnns Appendix 6 Appendix C Questions amp Answers eeeeee eer ieseeeee een enean nnn n aaa a aa nana anna Appendix 12 Table of contents for example Chapter 1 Introduction to C Language 1 1 Programming in C Language 1 2 Data Types 1 3 Operators 1 4 Coniro olStaiemeniS EO Example 1 4 1 Count Up if else statement sees nennen Example 1 4 2 Switchover of Arithmetic Operations 1 else if statement Example 1 4 3 Switchover of Arithmetic Operations 2 switch case statement Example 1 4 4 Finding Sum Total 1 while statement eseeesssseeseeeeeeenenn Example 1 4 5 Finding Sum Total 2 for statement cccccsssssseeeeeeceesseeeeeeseesseeeeeeseasseeeeeeees Example 1 4 6 Finding Sum Total 3 do while statement ccccceccceeeseeeeeeeeeeeeeeeeseeeeeeseeeeeeeeas To FUNCIONS m MRRRURNTUTM
6. expression 1 expression 2 Substitutes the value of expression 2 for expression 1 Adds the values of expressions 1 and 2 and expression 1 expression 2 substitutes the sum for expression 1 Subtracts the value of expression 2 from that of expression 1 expression 2 expression 1 and substitutes the difference for expression 1 l Multiplies the values of expressions 1 and 2 and x expression 1 x expression 2 substitutes the product for expression 1 m Divides the value of expression 1 by that of expression 1 Divides the value of expression 1 by that of expression 1 expression 2 expression 2 and substitutes the remainder for expression 1 expression 2 expression 2 and substitutes the quotient for expression 1 result for expression 1 ANDs the bits representing the values of expressions expression 1 amp expression 2 1 and 2 and substitutes the result for expression 1 ORs the bits representing the values of expressions 1 expression 1 expression 2 l and 2 and substitutes the result for expression 1 XORs the bits representing the values of expressions a expression 1 expression 2 l 1 and 2 and substitutes the result for expression 1 Shifts the value of expression 1 left by the amount lt expression 1 lt lt expression 2 equal to the value of expression 2 and substitutes the result for expression 1 Shifts the value of expression 1 right by the amount gt gt expression 1 g
7. denotes successive description unc1 a Descriptions entered even after line feed are func2 b assumed to be part of a continuous character func3 c string Enclose a complex statement with brackets T and s Figure 1 9 4 Example for defining a macro function Canceling definition undef identifier Replacement of the identifier defined in define is not performed after undef However do not use undef for the following four identifiers because they are the compiler s reserved words FILE Source file name LINE Line number of current source file DATE Compilation date TIME Compilation time 65 Introduction to C Language 1 9 Preprocess Commands 1 9 4 Conditional Compile NC30 allows you to control compilation under three conditions Use this facility when for example controlling function switchover between specifications or controlling incorporation of debug functions This section explains types of conditional compilation and how to write such statements Various conditional compilation Table 1 9 2 lists the types of conditional compilation that can be used in NC30 Table 1 9 2 Types of Conditional Compile if condition expression A If the condition expression is true not 0 NC30 compiles else block A if false it compiles block B endif ifdef identifier If an identifier is defined NC30 compiles block A if not else defined it compiles block B
8. 3 3 1 Basics of Real time OS 3 1 3 Interrupt Management In MR30 interrupt programs are called interrupt handlers This section explains the types of interrupt handlers available with MR30 and how the OS dependent interrupt handler one of these interrupt handlers is managed Types of interrupt handlers In MR30 the interrupt handlers are classified by whether or not they use a system call inside the OS The interrupt handlers that use a system call internally are called OS dependent interrupt handlers and those do not are called OS independent interrupt handlers The following explains the functions of the OS dependent interrupt handlers Table 3 1 4 Types of Interrupt Handlers These interrupt handlers use the system calls provided by MR30 Unlike interrupt programs they require processing for using system calls OS independent These interrupt handlers do not use the system calls provided by interrupt handler MR30 They function in the same way as interrupt programs OS dependent interrupt handlers OS dependent interrupt handler Unlike tasks the OS dependent interrupt handlers are not the subject of dispatching or scheduling operation therefore no TCBs are created for them The following describes the processing procedures for the OS dependent interrupt handlers Registers are saved Handler is executed using system call Registers are restored OS dependent interrupt handler terminating system call re
9. Canceling definition is partly revised DATA gt DATE 97 Example 2 3 1 Defining SFR Area Using pragma ADDRESS is partly revised unsiged gt unsigned Table 3 3 1 is partly revised asm inc inc gt asm sec inc 1 1 MITSUBISHI SEMICONDUCTORS PROGRAMMING MANUAL C LANGUAGE gt M16C 60 M16C 20 Series REV A1 Nov First Edition 2001 Editioned by Committee of editing of Mitsubishi Semiconductor User s Manual Published by Mitsubishi Electric Corp Semiconductor Marketing Division This book or parts thereof may not be reproduced in any form without permission of Mitsubishi Electric Corporation 2001 MITSUBISHI ELECTRIC CORPORATION Programming Manual C Language M16C 60 M16C 20 Series aa MITSUBISHI ELECTRIC CORPORATION HEAD OFFICE 2 2 3 MARUNOUCHI CHIYODA KU TOKYO 100 8310 JAPAN New publication effective Nov 2001 2001 MITSUBISHI ELECTRIC CORPORATION opecifications subject to change without notice
10. fnear_ROM fNROM Changes default attribute of ROM data to near default attribute of Changes default attribute of ROM data to near data to near fconst not ROM CNR pats not handle types specified by const as ROM ata Does not recognize variables specified by pragma fnot_address_volatile ADDRESS pragma EQU as those specified by volatile When referencing far type array if its total size is fsmall_array fSA within 64 Kbytes this option calculates subscripts in 16 bits Outputs 1 bit manipulating instruction in 16 bit fbit fB absolute addressing mode for variables located in near area Other Options fnot reserve inline fNRI Table B 10 Other Options Abbreviation Function Outputs C language source listing as comment in assembl dsource dS P J 9 9 y language source file list to be output Appedix 10 l Appendix B Appendix B NC30 Command Reference Command input example 1 Link the startup program ncrt0 a30 and a C language source program c src c to create an absolute module file test x30 9enc30 otest ncrt0 a30 c src c 9Specifies the output file name 2 Generate an assembler list file and a map file nc30 as30 In30 M c src c 9Specifies the options of as30 and In30 3 Output debug information to an assembly language source file attribute a30 nc30 g S ncrt0 a30 c src c Appedix 1 1 l Appendix C Appendix C Questions amp Answers
11. char buffi int buff2 3 ua cue buff1 2 bufi i buff 2 buff2 0 int buff2 buff2 1 10 20 30 buff2 2 B Figure 1 7 2 Declaration of one dimensional array and memory mapping Example 1 7 2 Finding Total Age of a Family 2 In this example we will find the total age of family members by using an array define MAX 3 Note define MAX 3 ad main void void main void int age MAX int age int total 0 eu int i Poker es Initialized simultaneously i when declared agel 0 29 A cu n RH 24 int total 0 By using an array it is age 2 4 IER possible to utilize a mus ees repeat statement where for i 0 i lt MAX i iii cen E li ira Eom the number of elements ng total ageli total ageli are used as variables Note define MAX 3 Synonym defined as MAX 3 Refer to Section 1 9 Preprocess Commands Example 1 7 2 Finding total age of a family 2 47 Introduction to C Language 1 1 7 Arrays and Pointers Two dimensional array A two dimensional array has a planar expanse comprised of columns and rows Or it can be considered to be an array of one dimensional arrays The following shows the declaration format of a two dimensional array Datatype array name number of rows number of columns To reference a two dimensional array add row numbers and column numbers to the array name as subscript Since both row and
12. include m30600 h void main void Heferences the SFR area P6 all 0x00 pragma ADDRESS P8 OSFOH pragma ADDRESS P9 OSF1H pragma ADDRESS PD8 OSF2H pragma ADDRESS PD9 OSFSH pragma ADDRESS TABSR 0380H pragma ADDRESS TAO 0386H Sets absolute pragma ADDRESS TAt1 0388H pragma ADDRESS TAOMR 0396H pragma ADDRESS TA1MR 0397H pragma ADDRESS TAOIC 0055H pragma ADDRESS TA1IC 0056H typedef union struct Type declaration for unsigned char bit operation unsigned char unsigned char unsigned char unsigned char unsigned char unsigned char unsigned char bit unsigned char all SFR ee ee ee Il SFR P6 P7 P8 P9 SFR PD6 PD7 PD8 PD9 SFR TABSR TAOMR TA1MR SFR TAOIC TA1IC unsigned int TAO TA1 Example 2 3 1 Defining SFR area using pragma ADDRESS 97 ROM ing Technology 2 2 3 Extended Functions for ROM ing Purposes 2 3 4 When Cannot Be Written in C Language There are some cases where hardware related processing cannot be written in the C language This occurs when for example processing cannot be finished in time or when one wishes to control the C flag directly To solve this problem NC30 allows you to write the assembly language directly in C language source programs inline assemble function There are two inline assemble methods one using the asm function and one using pragma ASM This section explains each method Writing only one line in assembly la
13. org OFFFDCH UDI word dummy int OVER FLOW Set the vector address of the lword dummy_int function used When not using BRK functions leave the field set as word dummy int dummy int ADDRESS MATCH lword dummy int SINGLE_STEP word dummy int WDT word dummy int DBC word dummy int NMI word dummy int RESET word Processing of dummy int ncrt0 a30 dummy int reit Figure 2 2 12 Setting fixed vector table 88 ROM ing Technology 2 2 Startup Program Precautions for operating in single chip mode When operating the M16C 60 M16C 20 in single chip mode note that the near ROM and the far ROM areas are not used Delete the ncrt0 a30 and the sect30 inc blocks shown in Figure 2 2 13 or turn them into comment statements ncrt0 a30 far area initialization program FAR area initialize sect30 inc near ROM area allocation Near ROM data area far RAM area allocation Far RAM data area ncrt0 a30 BZERO ebss Esz ebss E top BZERO ebss Osz ebss O top BCOPYedata Esz edata E top edata El top BCOPY edata Osz edata O top edata OI top Idc stack_top 1 sp Idc stack_top 1 fb sect30 inc section rom NE ROMDATA rom NE top Leave these lines as sectionrom NO ROMDATA comments sectiondata EI DATA org 10000H data FE top sectionbss FE DATA ALIGH bss FE top section data FO DATA data FE top sectionbss FO DATA bss FO top Figure 2 2 13 Example for w
14. p int int p jmptbl m Setting of jump address z p x y 3 m return Z Function call using a function pointer Example 1 7 3 Switching arithmetic operations using table jump 56 Introduction to C Language 1 1 8 Struct and Union 1 8 Struct and Union 1 8 1 Struct and Union The data types discussed hereto e g char signed int and unsigned log int types are called the basic data types stipulated in compiler specifications The C language allows the user to create new data types based on these basic data types These are struct and union The following explains how to declare and reference structs and unions From basic data types to structs otructs and unions allows the user to create more sophisticated data types based on the basic data types according to the purposes of use Furthermore the newly created data types can be referenced and arranged in an array in the same way as the basic data types Addresses Collectively managed Names Addresses Telephone numbers Dates of birth Dates of birth Basic data types More sophisticated elements of struct data types structs Figure 1 8 1 From basic data types to structs 57 Introduction to C Language 1 8 Struct and Union 1 8 2 Creating New Data Types The elements that constitute a new data type are called members To create a new data type define the members that constitute it This definition makes it possible to declare a data
15. use in handlers For details about the functionality of system calls refer to the MR30 manual ista tsk ichg pri irot rdq irel wai get tid isus tsk irsm tsk iwup tsk iset flg cir fig pol flg isig sem preq sem isnd msg prcv msg set tim get tim act cyc 149 Using Real time OS MR30 3 4 Building MR30 into Program Using NC30 Data exchange by using mail box Figure 3 4 10 shows an example for exchanging data between an OS dependent interrupt handler and a task by using a mail box In this description example data in length of 16 bits is used as a message In addition to this 16 bit long addresses can also be used as a message include lt mr30 h gt Hinclude id h void int hand void Prepares data used as a message int data1 The message data can be data or addresses in data1 0x10 length of up to 16 bits isnd_msg ID_mbx1 PT_MSG data1 Sends a message to mail box mbx1 The message data is cast by PT MSG j The type declaration of isnd msg system call is as follows ER isnd msg ID PT MSG void taski void Prepares data for receiving a message int data The message s data length must be matched to for 4 that of transmitted message rcu msg PT MSG amp data1 ID mbxl Waits for message from mail box mbx1 The variable to receive a message is cast by PT MSG The type declaration of rcv msg system call is as follows ER r
16. 4 short word 2 void main void union pack a b A 4 byte area is shared by all byte and word Figure 1 8 4 Declaring and referencing a union Column 7 7 Type definition oince structs and unions require the keywords struct and union there is a tendency that the number of characters in defined data types increases One method to circumvent this is to use a type definition typedef typedef existing type name new type name When the above description is made the new type name is assumed to be synonymous with the existing type name and therefore either type name can be used in the program Figure 1 8 5 below shows an example of how typedef can actually be used When using type definition the struct union tag name is unnecessary struct data typedef struct char a char a short b short b long c long c DATA js sdata sptr DATA sdata sptr Figure 1 8 5 Example for using type definition typedef 61 Introduction to C Language 1 1 9 Preprocess Commands 1 9 Preprocess Commands 1 9 1 Preprocess Commands of NC30 The C language supports file inclusion macro function conditional compile and some other functions as preprocess commands The following explains the main preprocess commands available with NC30 Preprocess command list of NC30 Preprocess commands each consist of a character string tha
17. 9 Pointer array declaration and initialization Note In NC30 the body data of a pointer array is located in the far area Consequently be sure to write far for the pointer For details refer to Section 2 3 1 Efficient Addressing 53 Introduction to C Language 1 7 Arrays and Pointers Pointer array and two dimensional array The following explains the difference between a pointer array and a two dimensional array When multiple character strings each consisting of a different number of characters are declared in a two dimensional array the free spaces are filled with null code O If the same is declared in a pointer array there is no free space in memory For this reason a pointer array is a more effective method than the other type of array when a large amount of character strings need to be operated on or it is necessary to reduce memory requirements to a possible minimum Two dimensional array char name 7 Norita Rumi Ryo ma E e Pointer array name 0 char far name 3 Address of N died name iEn Address of R Ryo ma b name 2 Address of R Figure 1 7 10 Difference between two dimensional array and pointer array 54 Introduction to C Language 1 7 Arrays and Pointers 1 7 6 Table Jump Using Function Pointer In assembly language programs table jump is used when switching processing load increases depending on the contents of some data The same effect as this can be o
18. C Language 1 1 Programming in C Language 1 1 3 Easily Understandable Program Since there is no specific format for C language programs they can be written in any desired way only providing that some rules stipulated for the C language are followed However a program must be easily readable and must be easy to maintain Therefore a program must be written in such a way that everyone not just the one who developed the program can understand it This section explains some points to be noted when writing an easily understandable program Rules on C language The following lists the six items that need to be observed when writing a C language program As a rule use lowercase English letters to write a program Separate executable statements in a program with a semicolon Enclose execution units of functions or control statements with brackets and Functions and variables require type declaration Reserved words cannot be used in identifiers e g function names and variable names Write comments between and Configuration of C language source file Figure 1 1 3 schematically shows a configuration of a general C language source file For each item in this file refer to the section indicated with an arrow Reading header file Refer to 1 9 Preprocess Commands Type declaration of functions used Refer to 1 5 Functions Macro definition Refer to 1 9 Preprocess Commands Declaration of external va
19. Either operator returns a logic 1 when a condition is met and a logic O when a condition is not met This section explains these relational and logical operators Relational operators These operators examine two expressions to see which is larger or smaller than the other If the result is true they return a logic 1 if false they return a logic O Table 1 3 7 Relational Operators Operator Description format Content True if the value of expression 1 is smaller than lt expression 1 lt expression 2 l l that of expression 2 otherwise false True if the value of expression 1 is smaller than or lt expression 1 lt expression 2 l l equal to that of expression 2 otherwise false True if the value of expression 1 is larger than that gt expression 1 gt expression 2 l l of expression 2 otherwise false True if the value of expression 1 is larger than or gt expression 1 gt expression 2 equal to that of expression 2 otherwise false True if the value of expression 1 is equal to that of expression 1 expression 2 l l expression 2 otherwise false True if the value of expression 1 is not equal to expression 1 expression 2 l l that of expression 2 otherwise false Logical operators These operators are used along with relational operators to examine the combinatorial condition of multiple condition expressions Table 1 3 8 Logical Operators l True if both expressions 1 and 2 are true
20. Here a brief explanation is made of MR30 s startup program Set main control registers Must be modified to suit the user s system Load data section data Clear bss section data Set system clock Must be modified to suit the user s system Initialize each peripheral I O Must be modified to suit the user s system Initialize each object Activate task place in READY state All tasks whose initial state was defined READY when registering tasks are placed in the READY state Consequently the task with the highest priority among them is placed in the RUN state Figure 3 3 1 Outline of processing performed by MR30 startup program 135 Using Real time OS MR30 3 3 3 Development Procedures Using MR30 Modification of startup program Before developing a program using MR30 the startup program provided by MR30 must be modified to suit the user s system The following lists the main points to be modified e Setting of processor mode register e Setting of interrupt vector table start address e Initialization of peripheral I Os used e Modification of memory map e Setting of processor mode register crt mr a30 Initialize the processor mode register and other registers that control the M16C 60 M16C 20 directly Figure 3 3 2 shows the lines to be modified and how to write new lines Program starts from this label after reset SYS INITIAL section MR KERNEL CODE ALIGN INITIAL Set the
21. Interrupt Processing 2 5 2 Registering Interrupt Processing Functions For interrupts to be serviced correctly in addition to writing interrupt processing functions it is necessary to register them in an interrupt vector table This section explains how to register interrupt processing functions in an interrupt vector table Registering in interrupt vector table When interrupt processing functions are written they must be registered in an interrupt vector table This can be accomplished by modifying the interrupt vector table in the sample startup program sect30 inc Follow the procedure described below to modify the interrupt vector table 1 Externally define the interrupt processing function names using the pseudo instruction OID 2 Change the dummy function names dummy int of the interrupts used to interrupt processing function names section vector variable vector table org VECTOR ADR word dummy int vector BRK Org VECTOR ADR 44 word dummy int DMAO for user word dummy int DMA1 for user word dummy int input key for user word dummy int A D Convert for user Org VECTOR ADR 68 word dummy int uartO trance for user word dummy int uartO receive for user word dummy int uart1 trance for user word dummy int uart1 receive for user tao _ta0 TIMER AO for user dummy int TIMER A1 for user dummy int TIMER A2 for user Registers function ta0 in dummy int T
22. Stack area void funci char x char y char z Return address NE Argument b Register H1 void func2 int Hegister R2 Argument n Figure 2 4 4 Example for passing arguments to functions 102 ROM ing Technology 2 4 Linkage with Assembly Language Rules for passing return values All return values except those expressed by a struct or union are stored in registers However different registers are used to store the return values depending on their data types The return values represented by a struct or union are passed via stored address and stack Namely an area to store a return value is prepared when calling a function and this address is passed via a stack as a hidden argument The called function writes its return value to the area indicated by the address placed in the stack when control returns from it Table 2 4 2 Rules for Passing Return Value Data type Returning method int short long struct union Store address is passed via a stack Prototype declaratione eee int func int int int func2 int void main void Register R1 nt m n int ans Register R2 Register RO Return value e When returned value is a struct struct tag_st char moji struct tag_st func char int suji Register R1 j Register R2 struct tag_st func int Argument b void main void Stack area Return char a address int b Address of struct tag st ret d
23. a set of processing if a ram1 P J with brackets and break a ram1 unsigned int ram1 Vi Figure 1 1 4 Example of programming style of C language program Introduction to C Language 1 1 1 Programming in C Language Method for writing a comment statement The method for writing a comment statement constitutes an important point in writing an easily readable program Program flow can be clarified by for example indicating the functionality of a file or that of a function as the header Example of file header FILE COMMENT sescsesiesksksese soke desse se sesesie e sts spe bee otote EEEE tese tese sisse e topo teo AM sessi ese pete epe K k k k k SystemName Test program FileName TEST C Version 1 00 CPU M30600M8 XXXFP Compiler NC30 Ver 1 00 OS Unused Programmer XXXX sesedespe esposte esp dese de pote epe esee pote poe se este e poesie EEE EEEE EEEE EEEE EEEE espe sje e poste senes sje esie sepes qe ee siete dee ese fe se he dee sesh k k k Copyright XXXX XXXXXXXXXXXXXXXXX CORPORATION sees esposte eee sede pee ee e sete petente sede se deste tese pe sepe s te pete te p bee te pete sspe ate e te e te espe siete peste pepe este spe te pe EEEE EEEE eee petes pee k k k History gt XXXX XX XX Start x FILE COMMENT EN D sce ke 2 22 2 2 2 2 s 2 sees seek ook ok ok ook a ote ok ok ok ok ok ok ok 2k ok ok 2k 2k ok 2k 2k ok obe ak ok 2k ak ok 2k 2k ok 2k 2k ok ok 2k ok kk
24. amp amp expression 1 amp amp expression 2 l P otherwise false False if both expressions 1 and 2 are false expression 1 expression 2 otherwise true False if the expression is true or true if the expression n expression is false 23 Introduction to C Language 1 3 Operators 1 3 5 Other Operators This section explains four types of operators which are unique in the C language Conditional operator This operator executes expression 1 if a condition expression is true or expression 2 if the condition expression is false If this operator is used when the condition expression and expressions 1 and 2 both are short in processing description coding of conditional branches can be simplified Table 1 3 9 lists this conditional operator Figure 1 3 3 shows an example for using this operator Table 1 3 9 Conditional Operator Condition expression Executes expression 1 if the condition expression expression 1 is true or expression 2 if the condition expression expression 2 is false Value whichever larger is selected e Absolute value is found pP Figure 1 3 3 Example for using conditional operator sizeof operator Use this operator when it is necessary to know the number of memory bytes used by a given data type or expression Table 1 3 10 sizeof Operator sizeof sizeof expression Returns the amount of memory used by the sizeof data type expression or data type in units of bytes 24 I
25. can be Data type Bit length expressed unsigned char char unsigned charg bits 0t025 to 255 unsigned short int 16 bits 0 to 65535 Integer Signed short nt signed short int int 32768 to 32767 LL 32 bits 32 bits Number of significant digits 9 64 bits Number of significant digits 17 long double 64 bits Number of significant digits 17 12 Introduction to C Language 1 2 Data Types Declaration of variables Variables are declared using a format that consists of a data type A variable name Example To declare a variable a as char type char a By writing data type A variable name initial value a variable can have its initial value set simultaneously when it is declared Example To set A to variable a of char type as its initial value char a A Furthermore by separating an enumeration of multiple variables with a comma variables of the same type can be declared simultaneously Example int i j Example inti 2 1 2 2 i XX Indeterminate unsigned int long n 0x10000 Denotes that this is the long type of data Figure 1 2 3 Declaration of variables Introduction to C Language 1 2 Data Types 1 2 3 Data Characteristics When declaring a variable or constant NC30 allows its data characteristic to be written along with the data type The specifier used for this purpose is called the type qualifier This section explains the data characteristics han
26. in NC30 Monadic arithmetic operators Binary arithmetic operators Shift operators Bitwise operators Relational operators Logical operators Assignment operators Conditional operator sizeof operator Cast operator Address operator Pointer operator Comma operator lt lt gt gt amp amp amp Note For address and pointer operators refer to Section 1 7 Arrays and Pointers 16 Introduction to C Language 1 3 Operators 1 3 2 Operators for Numeric Calculations The primary operators used for numeric calculations consist of the arithmetic operators to perform calculations and the assignment operators to store the results in memory This section explains these arithmetic and assignment operators Monadic arithmetic operators Monadic arithmetic operators return one answer for one variable Table 1 3 2 Monadic Arithmetic Operators variable prefix type t P yP Increments the value of an expression variable postfix type variable prefix type Decrements the value of an expression variable postfix type Returns the value of an expression after expression l HMM inverting Its sign When using the increment operator or decrement operator in combination with a assignment or relational operator note that the result of operation may vary depending on which type prefix or postfix is used when writing the operator Examples Prefix type The value is incremented or decreme
27. include id h static void task3 void No static type functions can be used as task j Figure 3 4 3 Precautions for writing tasks 1 regarding static type functions 144 Using Real time OS MR30 3 4 Building MR30 into Program Using NC30 Precautions for writing tasks 2 include lt mr30 h gt l External variables mode are not initialized include id h when this task is restarted RUN state after being terminated once idle state char mode 0 void taski void for Must a include lt mr30 h gt 73 ese IKe Hinclude id h char mode 0 void taski void mode 0 When using external and static variables in a task to be restarted initialize them in the task function for 3 if mode Figure 3 4 4 Precautions for writing tasks 2 initialization of variables in restarted task 145 Using Real time OS MR30 3 3 4 Building MR30 into Program Using NC30 Column Referenced range of variables scope Variables are referenced in different ranges depending on their storage class Table 3 4 3 and Figure 3 4 5 show the referenced range of variables that vary depending on the storage class Table 3 4 3 Referenced Range of Variables Storage class of variable Referenced range External variables Can be referenced in all tasks and handlers ic variables outside task SIAlIG Can be referenced in tasks and handlers within the same file and handler ic variables insid
28. the M16C 60 s fvector l M16C 20 sfixed vector deleted Stores interrupt programs functions Since the interrupt program ig specified by pragma INTERRUPT interrupt at any desired address in the M16C and pragma HANDLER This section is located in bank 0 of the 7700 family located varies with each type of microcomputer Appedix 3 l Appendix A Appendix A Functional Comparison between NC30 and NC77 Modified extended functions With the M16C 60 M16C 20 series banks and the m and x flags are nonexistent Therefore the definitions of the near far modifiers and part of functionality of the asm function have been modified Table A 2 Modified Extended Functions 1 Specify the addressing mode to 1 Specify the addressing mode to access data access data near Access 00000H through near Access addresses within the OFFFFH same bank far Access 00000H through far Access addresses outside the FFFFFH bank 2 All functions assume the far Specify whether the JSR or JSRL attribute instruction is used to call a function near JSR instruction is used far JSRL instruction is used near far modifier Write assembly language in C Write assembly language in C language language Specify auto variable by variable Specify auto variable by variable name name Partially suppress optimization Partially suppress optimization Specify register argument by Control m and x flags variable nam
29. the values expression 1 expression 2 l l l of expressions 1 and 2 after XORing each bit i l Returns the value of the expression after expression l DENM inverting its bits Shift Operators In addition to shift operation shift operators can be used in simple multiply and divide operations For details refer to Column Multiply and divide operations using shift operators Table 1 3 6 Shift Operators Shifts the value of expression 1 left by the expression 1 expression 2 amount equal to the value of expression 2 and returns the result Shifts the value of expression 1 right by the expression 1 gt gt expression 2 amount equal to the value of expression 2 and returns the result 20 Introduction to C Language 1 3 Operators Comparison between arithmetic and logical shifts When executing shift right note that the shift operation varies depending on whether the data to be operated on is singed or unsigned e When unsigned Logical shift A logic O is inserted into the most significant bit e When signed Arithmetic shift Shift operation is performed so as to retain the sign Namely if the data is a positive number a logic 0 is inserted into the most significant bit if a negative number a logic 1 is inserted into the most significant bit lt Unsigned gt lt Negative number gt lt Positive number gt unsigned int OxFC18 signed int OxFC18 signed int i OXOSE8 i 64520 i 1
30. type to allocate a memory area and reference it as necessary in the same way as the variables described earlier This section describes how to define and reference structs and unions respectively Difference between struct and union When allocating a memory area members are located differently for structs and unions 1 Struct Members are sequentially located 2 Union Members are located in the same address Multiple members share the same memory area Definition and declaration of struct To define a struct write struct struct structtag member 1 member 2 The above description creates a data type struct struct tag Declaration of a struct with this data type allocates a memory area for it in the same way as for an ordinary variable struct A struct tag A struct variable name 58 Introduction to C Language 1 8 Struct and Union Referencing struct To refer to each member of a struct use a period that is a struct member operator struct variable name member name To initialize a struct variable list each member s initialization data in the order they are declared with the types matched name a name struct person char name long number HS a number char section 5 int work year section 0 DEP section 1 a section 0 void main void l section 2 to struct person a b section 3 a section 4 2 section 4 Work year a work year If the area that contains name is
31. void or os j Figure 3 4 1 Example of task description Features of command expansion by task specification The functions specified in tasks differ from ordinary functions in the manner of command expansion as described below The frame base register FB is not saved to a stack When terminating the function an ext tsk system call is output 143 Using Real time OS MR30 3 4 Building MR30 into Program Using NC30 Precautions for writing tasks 1 Write tasks in function style At this time pay attention to the following Return values must be the void type e A function has one void or int type argument Only one argument can be specified When a task is invoked for the first time as argument of sta tsk system call MR30 can receive one integer type data as start code No static type functions can be defined as task See Figure 3 4 3 When a task is restarted the external variables used in the task and static variables are not initialized Initialize these variables back again See Figure 3 4 4 Figures 3 4 2 to 3 4 4 show description examples and the precautions for writing tasks include lt mr30 h gt include id h void taski void void task2 int code switch code N One integer type can be specified for argument Processing can be switched over by using start code Figure 3 4 2 Example of task description include lt mr30 h gt
32. when the access speed has priority pragma STRUCT tag s2 unpack struct tag_s2 int i char Declares inhibition Mapping of packing image 2 A struct s total size is adjusted to even bytes Figure 2 1 8 Inhibiting struct members from being packed 76 ROM ing Technology 2 1 Memory Mapping Optimizing mapping of struct members pragmaASTRUCTAtag name arrange This command statement allocates memory for the members of an even size before other members no matter in which order they are declared If this statement is used in combination with the pragma STRUCT unpack statement described above each member of an even size is mapped into memory beginning with an even address Therefore this method helps to accomplish an efficient memory access pragma STRUCT tag s3 arrange Members of even size are mapped first struct tag s3 darem dE Declares optimization Mapping Int of mapping image char c int k s3 Figure 2 1 9 Optimizing memory allocation for struct members 4 1 ROM ing Technology 2 2 2 Startup Program 2 2 Startup Program 2 2 1 Roles of Startup Program For a built in program to operate properly it is necessary to initialize the microprocessor and set up the stack area before executing the program This processing normally cannot be written in the C language Therefore an initial setup program is written in the assembly language separately from the C language source program This is
33. 0 is supplied and how it can be built into a system Supplied form of MR30 MR30 is supplied in library form This means that the library of MR30 is built into a system only when linking it Each system call of MR30 constitutes a library module Figure 3 2 1 shows the system call library provided by MR30 E Gt ee Task Task attendant Time Version management synchronization management management Interrupt Scheduler processing Figure 3 2 1 System call library provided by MR30 Incorporation into a system MR30 consists of a library of each system call Therefore when linking the entire system only the system calls written in the user program are built into the system Not all of MR30 is built into the system When viewed from the program side all system calls are handled as external functions i e functions prepared by MR30 131 Using Real time OS MR30 3 2 Method for Using System Calls 3 2 2 Writing a System Call This section explains how to write system calls necessary to use the real time OS by using the C language Basic method for writing a system call All system calls are handled as functions Therefore the method for using system calls in a program is the same as the one normally used for function calls include mr30 h void task1 void Include file required for using MR30 PIBC ISO Places its own task in WAIT state VA Figure 3 2 2 Writing a system call System ca
34. 000 i 1000 1111 1100 0001 1000 1111 1100 0001 1000 0000 0011 1110 1000 0111 1110 0000 1100 111111100000 1100 599 00000001 1111 0100 500 0011 1111 0000 0110 1111 1111 00000110 250 0000 0000 1111 1010 250 0001 1111 1000 0011 1111 1111 1000 0011 125 0000 0000 0111 1101 125 Logical shift Arithmetic shift positive or negative sign is retained Figure 1 3 2 Arithmetic and logical shifts 21 Column Introduction to C Language 1 3 Operators Multiply and divide operations using shift operators Shift operators can be used to perform simple multiply and divide operations In this case operations are performed faster than when using ordinary multiply or divide operators Considering this advantage NC30 generates shift instructions instead of multiply instructions for such operations as 2 14 and 8 Multiplication Shift operation is performed in combination with add operation a x2 gt a 3o a 4 a a 8o a 20 gt a 1 a 1 a a lt lt 2 a lt lt 2 a lt lt 1 a a lt lt 3 a lt lt 4 a lt lt 2 Division The data pushed out of the least significant bit makes it possible to know the remainder a Ao a gt gt 2 a 8B gt a gt gt 3 a 16 a gt gt 4 22 Introduction to C Language 1 3 Operators 1 3 4 Operators for Examining Condition Used to examine a condition in a control statement are relational operators and logical operators
35. 11 2 5 Mten pt Processing EET DEED mI 112 2 5 1 Writing Interrupt Processing Functions essai eucushsEtestapzotekeinm bxdvbuate hingtetamsunderraaa egeta pu od bou Aa 112 2 5 2 Registering Interrupt Processing Functions esses 115 2 5 3 Example for Writing Interrupt Processing Function eeeeeeee eene 116 Chapter 3 Using Real time OS MR30 3 1 Basics of Real time OS T IT m 121 3 1 1 Real time OS and Task NN 121 3 1 2 Functions of Real time OS sssssssssssssssssessesennee nennen nnnm nnns nan nnns nna nnn rne 124 3 1593 JREOTEHD E Managerni Mi asseris arion ien E E n e eE ARR 127 3 1 4 Special Handlers MEO EL OO EOS 130 3 2 Method for USING System Calls inris tex nuu uioutu mex de indio gu nai mu rU rs dud ER KU Ev Duc du CE cuu uS 191 SPAN MIO Sy ESTNE Tm 131 3 2 2 Writing SUI A NEN RR Um 192 3 3 Development Procedures Using MR30 ccccesseccccesececeeeeeeeeceeseeeeseaueeeessageceeseageeeessaaeeesens 135 3 3 1 Files Required during Development ccccccccseeeeecsesseeecseeececesseeeeeseaseeesseaueesseseaeeessaaass 135 3 3 2 Flow of Development Using MR30 seeessssesssseseee nnne nnne nennen nnne 140 3 4 Building MR30 into Program Using NC3S0 eccleeeeeeeeeeeen eese nennen nenne nnn nnn 141 3 41 Wri ng Program Using NO3 141 34 2 Witing Tasks Using NOIQ
36. Appendix C Questions amp Answers Transferring copying structs lt Question gt What method can be used to transfer copy structs Answer 1 When transferring structs of the same definition Use a struct vs variable name and a assignment operator to transfer the structs 2 When transferring structs of different definitions Use a assignment operator for each member to transfer the structs struct tagi Definition of struct int mem1 char meme int mems le struct tag2 int mem1 char meme int mem3 js near struct tag1 near s1tl near s2t1 near struct tag2 near s1t2 far struct tag1 far s t far s2t1 main 1 For structs of the same definition near siti mem1 0x1234 4OCan be transferred using a struct vs near_sitl mem2 A variable name and a assignment operator near_s1t1 mem3 0x5678 irrespective of allocated areas Transferring structs of the soz amp definition near s2t1 near siti 7 near gt near far s1t1 near s1 t1 near gt far near s2t1 far s1t1 far near far s2t1 far s1t1 far far Transferring structs of different definitions near s1t2 mem1 near s1t1 mem l near s1t2 mem2 near s1t mem 2 near s1t2 mem3 near s1t1 mem3 2 For structs of different definitions ransfer the structs one member a
37. Attribute If any of these default near far attributes needs to be modified specify the following startup options when starting up NC30 ffar RAM HFRAM Changes the default attribute of RAM data to far fnear ROM fNROM Changes the default attribute of ROM data to near 90 ROM ing Technology 2 3 Extended Functions for ROM ing Purposes near far of variables storage class A type specifier A near far A variable name Unless near far is specified when declaring type RAM data is located in the near area and RAM data with the const modifier specified and ROM data are located in the far area static static static static int data int near n data int far f data const int c data 0x1234 Figure 2 3 1 near far of static variables opecification of near far for automatic variables does not have any effect at all All automatic variables are located in the stack area What is affected by this specification is only the result of the address operator amp void func void in t addr far near i near amp i near gt 16 bits long far i far amp i far gt 20 bits long Pointer variable for near area is available aaar near described later addr near amp i near addr far 2 amp i far Warning occurs Substituted by ignoring upper address Figure 2 3 2 near far of automatic variables 91 ROM ing Technology 2 3 Extended Functions f
38. Changes for the Better MITSUBISHI 16 BIT SINGLE CHIP MICROCOMPUTER M16C FAMILY M16C 60 M16C 20 Series lt C language gt Programming Manual http www infomicom maec co jp indexe htm Before using this material please visit the above website to confirm that this is the most current document available 9 MITSUBISHI REV A1 ELECTRIC Revision date Nov 12 2001 Keep safety first in your circuit designs Mitsubishi Electric Corporation puts the maximum effort into making semiconductor prod ucts better and more reliable but there is always the possibility that trouble may occur with them Trouble with semiconductors may lead to personal injury fire or property damage Hemember to give due consideration to safety when making your circuit designs with ap propriate measures such as i placement of substitutive auxiliary circuits ii use of non flammable material or iii prevention against any malfunction or mishap Notes regarding these materials These materials are intended as a reference to assist our customers in the selection of the Mitsubishi semiconductor product best suited to the customer s application they do not convey any license under any intellectual property rights or any other rights belonging to Mitsubishi Electric Corporation or a third party Mitsubishi Electric Corporation assumes no responsibility for any damage or infringement of any third party s rights originating in the use of any pro
39. Conversely if excessively large it means wasting memory This section explains how to estimate an appropriate stack size Items that use a stack The following items use a stack 1 Automatic variable area Temporary area used for complex calculation 2 3 Return address 4 Old frame pointer 5 Arguments to function File for displaying stack sizes used Calculate the stack sizes used by each function Although it can be estimated from program lists there is a more convenient way to do it Specify a startup option fshow stack usage when starting up NC30 It generates a file xxx stk that contains information about the stack sizes used However this information does not include the stacks used by assembly language subroutine call and inline assembler Calculate the stack sizes used for these purposes from program lists Information on function func lt stk file gt Return address Old frame pointer lt Stack image gt Nen FUNCTION func context 5 bytes Automatic variable auto 3 bytes temporary area Automatic variable f8regSize 0 bytes Old frame pointer 6 bytes PUSH amp CALL func Return address Aai ees Stack sizes used when calling subordinate function used for argument Figure 2 2 2 Stack size usage information file 80 ROM ing Technology 2 2 Startup Program Calculating the maximum size of stacks used Find the maximum size of stacks used from the stack sizes used b
40. IMER A3 do em TAO interrupt dummy int TIMER A4 for user Figure 2 5 4 Interrupt vector table sect30 inc 115 ROM ing Technology 2 5 nterrupt Processing 2 5 3 Example for Writing Interrupt Processing Function The program shown in this description example counts up the content of counter each time an INTO interrupt occurs Writing interrupt processing function Figure 2 5 5 shows an example of source file description Prototype declaration x 22 2 a 2 2 esee eee e 2K KK 2K KKK aK ok ok ok ok ok EKK k kk void intO void pragma INTERRUPT intO ks 2 KG se eoe beoe obe ook ok KK KK aK ok a a oe sese sk KK oe oe oko ote o oot ok ok ok 2 ok ok ok ok oi ok ok 2k ok 2k 2k 2k 2k 2k unsigned int counter 0 void intO void Interrupt function if counter lt 9 counter else counter 0 void main void INTOIC 1 Setting interrupt level asm fset i Enabling interrupt while 1 Interrupt waiting loop Figure 2 5 5 Example for writing interrupt processing function 116 ROM ing Technology 2 2 5 Interrupt Processing Registering in interrupt vector table Figure 2 5 6 shows an example for registering the interrupt processing functions in an interrupt vector table section vector variable vector table Org VECTOR_ADR Org VECTOR_ADR 68 word dummy int UARTO trance for user word dummy int UARTO receive for us
41. Initial values data section Figure 2 1 3 Mapping data into sections by type int i k stack section Compiler does not generate ROM ing Technology 2 1 Memory Mapping Sections attributes The sections generated by NC30 are further classified into smaller sections by their attributes i e whether or not they have initial value in which area they are mapped and their data size Table 2 1 2 lists the symbols representing each attribute and its contents Table 2 1 2 Sections attributes Applicable Attribute Content section name Section to noid data s initiat vae sat Section to hold data s initial value N near attribute 64 byte area at absolute addresses from 0 to OFFFF F far attribute entire 1 Mbyte memory area from address 0 to FFFFF data bss rom S SBDATA attribute area where SB relative addressing can be used E Data size is even data bss rom O Data size is odd For details on how to specify these attributes refer to Section 2 3 1 Efficient Addressing Rule for naming sections The sections generated by NC30 are named after their section base name and attributes Figure 2 1 4 shows a combination of each section base name and attributes Section name section base name attribute Sec onbasename near attribute far attribute EN EN SBDATA attribute 4 EN Even size data Odd size data Contains initial value Figure 2 1 4 Rule for assigning section
42. a near area struct person becomes a 13 byte type if a far area it becomes a 15 byte type nitialization of struct variable struct person a SATOH 10025 T511 25 Address a number a section 0 to a section 4 a work year Figure 1 8 2 Struct declaration and memory mapping 59 Introduction to C Language 1 8 Struct and Union Example for referencing members using a pointer To refer to each member of a struct using a pointer use an arrow gt struct person e long number of S char section 5 int work year EE struct person a SATOH 10025 T511 25 E p section 0 void main void to p section 4 struct person p p amp a p gt work_year Figure 1 8 3 Example for referencing members using a pointer 60 Introduction to C Language 1 8 Struct and Union Unions Unions are characteristic in that an allocated memory area is shared by all members Therefore it is possible to save on memory usage by using unions for multiple entries of such data that will never exist simultaneously Unions also will prove convenient when they are used for data that needs to be handled in different units of data size e g 16 bits or 8 units depending on situation To define a union write union Except this description the procedures for defining declaring and referencing unions all are the same as explained for structs union pack long all char byte
43. absolute addresses using a pointer Specifying absolute addresses using an extended function pragma ADDRESS pragma A ADDRESS A variable name A absolute address The above declaration causes a variable name to be located at an absolute address oince this method defines a variable name as synonymous with an absolute address there is no need to allocate a pointer variable area as required for the above method Therefore this method helps to save memory usage As30 format of numeric description must be followed pragma ADDRESS port4 03e8h Expansion image char near port4 void func void por vESH SON mov b 0 port4 port4 0x00 pragma ADDRESS is effective for only variables defined outside a function and those declared in a function as being a static variable Figure 2 3 9 Specifying absolute addresses using pragma ADDRESS 96 ROM ing Technology 2 3 Extended Functions for ROM ing Purposes Example 2 3 1 Defining SFR Area Using pragma ADDRESS The extended function pragma ADDRESS can be used to set the SFR area For this method of SFR setting normally prepare a separate file and include it in the source program The following shows one example of an SFR area definition file Reads in the SFR area definition file SFR area definition file lt m30600 h gt lt Source file gt pragma ADDRESS P6 OSECH pragma ADDRESS P7 OSEDH pragma ADDRESS PD6 OSEEH pragma ADDRESS PD7 OSEFH
44. ala ret data _ l_ data func a b ret_data Body Figure 2 4 5 Example for passing return value 103 ROM ing Technology 2 4 Linkage with Assembly Language Rules for symbol conversion of functions into assembly language In NC30 the converted symbols differ depending on the properties of functions Table 2 4 3 lists the rules for symbol conversion Table 2 4 3 Rules for Symbol Conversion Function type Conversion method Arguments passed via register Functions are prefixed with Arguments passed via stack No argument oragma INTERRUPT pragma PARAMETER Functions are prefixed with Column A measure for calling functions faster A function call requires stack manipulation for the return values and arguments to be passed from a function to another This takes time before the actual processing can be performed Consequently the via register transfer reduces the time required for procedures from calling to processing because it involves less stack manipulation than the other method To reduce this difference in time further NC30 provides a facility called inline storage class When functions are specified to be an inline storage class NC30 generates code for them as macro functions when compiling the program This means that ordinary stack manipulation is nonexistent and that processing in the called function can be executed immediately after a call Code
45. andler description include lt mr30 h gt include id h void int hand void Figure 3 4 6 Example for writing OS dependent interrupt handler Features of command expansion in OS dependent interrupt handler An OS dependent interrupt handler and its specified function are expanded into instructions that perform the following Save all registers to the stack Perform interrupt handler entry processing for MR30 When terminated restore all registers from the stack Terminate the handler by using a ret int system call Note The method for writing OS independent interrupt handlers is the same as one that is written in Section 2 5 Interrupt Processing 147 Using Real time OS MR30 3 4 Building MR30 into Program Using NC30 Precautions for writing OS dependent interrupt handlers Write OS dependent interrupt handlers in function style At this time pay attention to the following Only void type return values are valid Only void type arguments are valid No static type functions can be defined e Only those system calls that are usable in handlers can be used in the OS dependent interrupt handler include lt mr30 h gt include id h Only void type return values and arguments as aos for OS dependent interrupt andlers void int hand void iwup tsk ID task1 i iue In an OS dependent interrupt handler use those system calls that are usable in handlers Fig
46. ariables are global variables that can be referenced from any function following the declaration Conversely internal variables are local variables that can be effective in only the function where they are declared following the declaration int main void int func void External to function int tmp Effective range int main void of tmp int a Internal to function Effective range of a External to function int func void int b Internal to function Effective range of b Figure 1 6 2 External and internal variables Storage class specifiers The storage class specifiers that can be used for variables are auto static register and extern These storage class specifiers function differently when they are used for external variables or internal variables The following shows the format of a storage class specifier storage class specifier A data type A variable name 42 Introduction to C Language 1 1 6 Storage Classes Storage classes of external variable If no storage class specifier is added for an external variable when declaring it the variable is assumed to be a global variable that is effective in the entire program On the other hand if an external variable is specified of its storage class by writing static when declaring it the variable is assumed to be a local variable that is effective in only the file where it is declared Write the specifier extern when using an external var
47. brary name gt Specifies library that is used when linking Assemble and link options Table B 8 Assemble and Link Options Specifies options of assemble command as30 When passing two or as30A lt Option gt l l l more options be sure to enclose them with double quotations In30A Option l l options be sure to enclose them with double quotations naoa lt opion gt Specifies options of link command In30 When passing two or more Appedix 9 l Appendix B Appendix B NC30 Command Reference Generated code modifying options Table B 9 Generated Code Modifying Options Abbreviation Enables fnot_reserve_asm fansi None fnot reserve far and near fnot reserve inline and fextend to int Frees asm from reserved word Only asm is fnot reserve asm fNRA pom valid Frees far and near from reserved words Onl fnot_reserve far and near fNRFAN l ny _far and near are valid Frees inline from reserved word Only inline is valid h f sten to ini ETI Expands char type data to int type before operating on it h ichar enumieraior CE Handles ene type as being unsigned char type and not as int type Locates all data in odd attribute section without fno_even fNE separating them between odd and even when outputting data i tputs stack usage conditions to file extension fshow stack usage fSSU d E 9 ffar RAM fFRAM a default attribute of RAM data to far
48. btained in C language programs also by using the pointer array described above This section explains how to write a table jump using a function pointer What does a function pointer mean A function pointer is one that points to the start address of a function in the same way as the pointer described above When this pointer is used a called function can be turned into a parameter The following shows the declaration and reference formats for this pointer Declaration format Type of return value function pointer name data type of argument Reference format Variable in which to store return value function pointer name argument 55 Introduction to C Language 1 7 Arrays and Pointers Example 1 7 3 Switching Arithmetic Operations Using Table Jump The method of calculation is switched over depending on the content of variable num Prototype declaratione eee int calc f int int int int add f int int sub f int int int mul f int int div f int int l Jump table secco int const jmptbl int int 2 add f sub f mul f div f Function pointers arranged in an array void main void Start address jmptbl 0 ot agq p int x 10 y 2 int num val Start address jmptbll 1 of sub f num 22 if num lt 4 Start address val calc f num x y jmptbl 2 of mul f jmptbl 3 Start address of div f calc f int m int x int y int z int
49. ceneseatecesenccaededesanceaseuncnats 72 2 1 3 Control oFMermory Mapping edocuit ntes rnt Cdditbdetu dices e ine cU St EMO EU ee seeeen secs 74 2 1 4 Controlling Memory Mapping Of Struct iussi ice Eoo rrr natem rt n oan inertes 76 2 2 Satu POG AIM uoueeocescusa uemuuiuidue e ouU De aN 78 2 2 1 Holes OF Stanup Progra uses ceetomemibut sum de SE SERe doses aT E a E utem esteem Sr ud nep ue UME 78 2 2 2 Estimating Stack Sizes SOC uoce utes onm ont reca ixi ossia Uc adden ainda ipta iaai ainiai ienasi ninaa 80 2 2 3 Creating Startup Program asocio emt ues tutie rte sot rx ud Le euo Free ax ba nei d osibad Uo ore bi ne edes ursus 83 2 3 Extended Functions for ROM ing Purposes eeeeeeeeee ee eeee eren enne nnn 90 2 3 1 Efficient Addressing EET NUNEEROERNR 90 232 Handing OF TEE T E E E EEA 94 233 ONION OF VO ANC ACS osissa eE EEEE REA ESEE 96 2 3 4 When Cannot Be Written in C Language ssseessssssseeene nennen nennen nene nnns 98 2 4 Linkage with Assembly Language 11 ec leeeee iere reinen ene e nennen nnne n anna nnns nnn 100 2 4 1 Interface between Functions cccccccsseeceeceeeeeeeceeeeeecaeeeeeeeceueeeecsasseeesseaecesseeneeeessaneeeseaas 100 2 4 2 Calling Assembly Language from C Language seseeeeseeeeeeeennnnnn 105 2 4 3 Calling C Language from Assembly Language ccccccsseeeeeeeeeeeeeeeeeeeeaaeeeeeeesenaaeeeeeeesaas 1
50. column numbers begin with 0 the last row or column number is 1 less than the number of rows or columns Concept of two dimensional array Columns Hows Row0 RowO RowO RowO l column 0 column 1 column 2 column 3 Row 1 Row 1 Row 1 Row 1 column 0 column 1 column 2 column 3 Row 2 Row 2 Row 2 Row 2 column O column 1 column 2 column 3 Declaration and initialization of two Declaration and initialization of two dimensional array dimensional array buff 1 0 1 Ca bo ly buff 1 0 2 pr ues us buff 1 1 buff 1 1 0 buff 1 1 1 buff 1 1 2 N buff 2 0 0 i o S IV l int buff 2 2 3 int buff 2 3 10 20 30 40 50 60 buff 2 0 1 b L7 When initializing a two buff 2 0 2 dimensional array simultaneously with buff2 1 gt declaration buff 2 1 0 specification of the number of rows can be omitted Number of buff 2 1 1 columns cannot be omitted buff 2 1 2 Figure 1 7 3 Declaration of two dimensional array and memory mapping 48 Introduction to C Language 1 7 Arrays and Pointers 1 7 3 Pointers A pointer is one that points to data i e it indicates an address A pointer variable which will be described here handles the address at which data is stored as a variable This is equivalent to one that is referred to as indirect addressing in the assembly language This section explains how to declare and reference a pointer var
51. cv msg PT MSG v ID Uses the data from OS dependent interrupt handler Figure 3 4 10 Example for data exchange by using a mail box 150 Using Real time OS MR30 3 3 4 Building MR30 into Program Using NC30 3 4 4 Writing Cyclic and Alarm Handlers This section explains how to write cyclic and alarm handlers and the precautions for writing these handlers Method for writing cyclic and alarm handlers Those system calls that are usable in handlers can be used in cyclic and alarm handlers and the specified functions Figure 3 4 11 shows an example for writing cyclic and alarm handlers include lt mr30 h gt include id h void cyc hand void j Figure 3 4 11 Example for writing cyclic and alarm handlers The cyclic and alarm handlers serve as the functions that are called in the system clock interrupt handler provided by MR30 Features of command expansion The functions specified in cyclic and alarm handlers are expanded into instructions that perform the following Terminate the handler by using an rts instruction Subroutine return instruction for the M16C 60 M16C 20 or an exitd instruction function return instruction for the M16C 60 M16C 20 151 Using Real time OS MR30 3 3 4 Building MR30 into Program Using NC30 Precautions for writing cyclic and alarm handlers Write the cyclic and alarm handlers in function style At this time pay attention to the following Only void type r
52. d refers to using structs to assign bit symbols The following shows the format of bit symbol assignment struct tag type specifier A bit symbol number of bits When referencing a bit symbol separate it with a period when specifying it as in the case of structs and unions variable name bit symbol Memory allocation for a declared bit field varies with the compiler used NC30 has two rules according to which memory is allocated for bit fields Figure 2 3 6 shows an example of actually how memory is allocated 1 Allocated sequentially beginning with the LSB 2 Different type of data is located in the next address The size of the allocated area varies with each data type struct ex char a 1 6 5 4 3 2 1 0 char b 1 char d 1 sO studs on sf stb int b12 2 char 63 1 s1 Memory is allocated for each data type as follows char type 1 byte int type 2 bytes long type 4 bytes Figure 2 3 6 Example of memory allocation for bit fields 94 ROM ing Technology 2 2 3 Extended Functions for ROM ing Purposes Generating bit instruction pragma BIT NC30 s bit field is such that although bit symbols can be handled in the program it is an arithmetic logic instruction and not a bit instruction that is generated To output a code efficient direct 1 bit instruction write an extended function pragma BIT along with bit field declaration Figure 2 3 7 shows an example o
53. declaration prototype declaration must be entered first The type of function refers to the data types of the arguments and the returned value of a function The following shows the format of function declaration prototype declaration data type of returned value function name list of data types of arguments If there is no returned value and argument write the type called void that means null Function definition In the function proper define the data types and the names of dummy arguments that are required for receiving arguments Use the return statement to return the value for the argument The following shows the format of function definition data type of return value function name data type of dummy argument 1 dummy argument 1 return return value Function call When calling a function write the argument for that function Use a assignment operator to receive a return value from the called function function name argument 1 When there is a return value variable function name argument 1 38 Introduction to C Language 1 5 Functions Example for a function In this example we will write three functions that are interrelated as shown below No argument No return value Main function main char type int type No return value Function 2 func 2 int type Function 1 func 1 Prototype declaration void main void int func in
54. dimensional array mtx can be obtained by mtx 1 amp is unnecessary Figure 1 7 7 Pointer variables and two dimensional array 51 Introduction to C Language 1 7 Arrays and Pointers Passing addresses between functions The basic method of passing data to and from C language functions is referred to as Call by Value With this method however arrays and character strings cannot be passed between functions as arguments or returned values Used to solve this problem is a method known as Call by Reference which uses a pointer variable In addition to passing the addresses of arrays or character strings between functions this method can be used when it is necessary to pass multiple data as a returned value Unlike the Call by Value method this method has a drawback in that the independency of each function is reduced because the data in the calling function is rewritten directly Figure 1 7 8 shows an example where an array is passed between functions using the Call by Reference method Calling function Called function define MAX 5 void cls str char void main void char str MAX cls str str ia ra ae ai p i 0 The array s start address is passed U The array body is operated on Figure 1 7 8 Example of Call by Reference for passing an array Column Passing data between functions at high speed In additi
55. dinary function procedures For both arguments and return values void is only the valid type of interrupt processing functions If any other type is declared NC30 generates a warning when compiling the program pragma INTERRUPT intr section program glb _ intr T Saves all registers void intr void intr Expansion image pushm HO H1 R2 H3 AO A1 SB FB Interrupt processing Interrupt processing Restores all registers popm RO R1 R2 R3 AO A1 SB FB Returns by reit instruction Figure 2 5 1 An image depicting expansion of interrupt processing function Only the void type is valid for both arguments and return values 112 ROM ing Technology 2 2 5 Interrupt Processing Writing interrupts that need to be invoked in short time pragma INTERRUPT B The M16C 60 M16C 20 has a facility to switch over the register banks while at the same time protecting register contents etc and making it possible to reduce the time until an interrupt handler is invoked To utilize this facility write a command statement as follows oragma A INTERRUPT B A interrupt function name When an interrupt function is declared as shown above NC30 generates instructions to switch over the register banks in place of instructions to save and restore the registers However since the M16C 60 M16C 20 register banks consist of only bank 0 and bank 1 only one interrupt can be specified at a time 9 Therefore use this fac
56. dled by NC30 and how to specify a data characteristic Specifying that the variable or constant is singed or unsigned data singed unsigned qualifier Write the type qualifier signed when the variable or constant to be declared is signed data or unsigned when it is unsigned data If neither of these type specifiers is written when declaring a variable or constant NC30 assumes that it is signed data for only the data type char or unsigned data for all other data types void main void Synonymous with unsigned char a char a signed char s a b Synonymous with signed int b unsigned int u b Figure 1 2 4 Example for writing type qualifiers signed and unsigned Specifying that the variable or constant is constant data const qualifier Write the type qualifier const when the variable or constant to be declared is the data whose value does not change at all even when the program is executed If a description is found in the program that causes this constant data to change NC30 outputs a warning void main void chara 10 constcharc a 20 a C 95 Warning is generated a Figure 1 2 5 Example for writing the type qualifier const 14 Introduction to C Language 1 2 Data Types Inhibiting optimization by compiler volatile qualifier NC30 optimizes the instructions that do not have any effect in program processing thus preventing unnecessary instruction code from being genera
57. duct data diagrams charts programs algorithms or circuit application examples contained in these materials All information contained in these materials including product data diagrams charts pro grams and algorithms represents information on products at the time of publication of these materials and are subject to change by Mitsubishi Electric Corporation without notice due to product improvements or other reasons It is therefore recommended that customers contact Mitsubishi Electric Corporation or an authorized Mitsubishi Semiconductor product distributor for the latest product information before purchasing a product listed herein The information described here may contain technical inaccuracies or typographical errors Mitsubishi Electric Corporation assumes no responsibility for any damage liability or other loss rising from these inaccuracies or errors Please also pay attention to information published by Mitsubishi Electric Corporation by various means including the Mitsubishi Semiconductor home page http www mitsubishichips com When using any or all of the information contained in these materials including product data diagrams charts programs and algorithms please be sure to evaluate all informa tion as a total system before making a final decision on the applicability of the information and products Mitsubishi Electric Corporation assumes no responsibility for any damage liability or other loss resulting from the i
58. e asm function Added extended functions For NC30 the compiler s extended functions have been added to support the features of the M16C 60 M16C 20 series such as bit manipulating instructions and SB relative addressing Furthermore to accommodate the M16C 60 M16C 20 series s versatile interrupt processing new extended functions are provided for writing interrupt programs that use software interrupts or register banks Moreover the extended functions now include an inline storage class and an inline assemble function pragma ASM making it possible to take full advantage of the M16C 60 M16C 20 series capabilities Table A 3 Added Extended Functions pragma ASM to Specifies area where statements are written in assembly pragma ENDASM language Declares that the variable is in an area where 1 bit manipulating instruction in 16 bit absolute addressing mode can be used pragma SBDATA Declares that SB relative addressing can be used for the data pragma INTERRUPTUB men calling ete function it switches over register banks instead of saving registers to stack pragma INTCALL Declares function that calls software interrupts int instruction pragma BIT Appedix 4 l Appendix A Appendix A Functional Comparison between NC30 and NC77 Deleted extended functions The extended functions of NC77 listed in Table A 4 are not supported by NC30 because they are used to operate on the registers or flags that do not exist in
59. e 3 1 3 Main System Calls for Object Manipulation Task Task management Task attendant sta tsk Activates a task READY state ext tsk Terminates its own task normally DORMANT state Task on E slp tsk Places its own task in WAIT state synchronization Synchronization and set flg communication Event flag wai flg Semaphore sig sem wai sem Mail box snd msg rcv msg OD wup tsk Places WAIT task in READY state Sets an event flag If there is a task waiting for an event flag this system call activates it READY state Waits for an event flag WAIT state If the event flag is already set this system call continues processing Frees a semaphore incrementing semaphore counter by 1 If there is a task waiting for a semaphore this system call activates it READY state In this case the semaphore does not change If the semaphore counter is already 0 this system call waits WAIT state If not O it decrements the semaphore counter by 1 and continues processing Sends a message to a mail box If there is a task waiting for a message this system call activates it READY state and passes the message If there is no waiting task the message is kept in the mail box Receives a message from a mail box If there is no message this system call waits WAIT state If there is already a message it receives the message and continues processing Using Real time OS MR30
60. e amount of stacks used Sample startup program ncrt0 a30 sect30 inc Standard libraries Standard library source files Figure 1 1 1 NC30 product list Introduction to C Language 1 1 Programming in C Language Creating machine language file from source file Creation of a machine language file requires startup programs written in the assembly language in addition to the source file that contains a C language program Figure 1 1 2 shows a tool chain necessary to create a machine language file from a C language source file C language source file Compile driver nc30 Preprocessor ccp30 Startup programs ncrtO0 a30 Compiler main unit ccom30 Assembly Assembly language language source file source file Stack size calculating utility stk30 eie MEE b 7777 7 lo ans righ sais T Relocatable Relocatable Stack usage loraries file file E calculation result HAC display file m m X m ee eee ee ee ee ee I Helocatable assembler as30 Linkage editor In30 Load module converter Imc30 Machine i language file B9 To ROM Files prepared by the Sofware Software included in NC30 user including libraries product package Ferm Files aenerated bv NC30 Software included in AS30 9 y software product package Ll l Figure 1 1 2 Creating machine language file from C language source file Introduction to
61. e constants J single character Integer constants Integer constants can be written using one of three methods of numeric representation decimal hexadecimal and octal Table 1 2 1 shows each method for writing integer constants Constant data are not discriminated between uppercase and lowercase Table 1 2 1 Method for Writing Integer Constants Normal mathematical notation nothing added 127 127 56 Numerals are preceded by 0x or 0X zero eks Ox3b OX3B Numerals are preceded by O zero 07 041 Real constants Floating point constants Floating point constants refer to signed real numbers that are expressed in decimal These numbers can be written by usual method of writing using the decimal point or by exponential notation using e or E Usual method of writing Example 175 5 0 007 Exponential notation Example 1 755e2 7 0E 3 Single character constants Single character constants must be enclosed with single quotations In addition to alphanumeric characters control codes can be handled as single character constants Inside the microcomputer all of these constants are handled as ASCII code as shown in Figure 1 2 1 Memory J integer Single character constant Integer constant Figure 1 2 1 Difference between 1 and 1 10 Introduction to C Language 1 2 Data Types Character string constants A row of alphanumeric characters or control codes enclosed with do
62. e objects 140 Using Real time OS MR30 3 3 4 Building MR30 into Program Using NC30 3 4 Building MR30 into Program Using NC30 3 4 1 Writing Program Using NC30 NC30 provides extended functions in order for MR30 to be built into a program The extended functions for MR30 are written into a specific file by using MR30 configurator Consequently once a specific file is included in the program there is no need to write the extended functions in an existing program However Mitsubishi recommends that the meaning of the extended functions be understood The following explains how to build MR30 into a program using NC30 Files to be included To create a program with built in MR30 include the required files at the beginning of the program These include files contain a description of definitions necessary to build MR30 into a program Table 3 4 1 Include Files Necessary to Use MR30 Contains definitions required for MR30 and declares system call prototype Rewrites object IDs used in program Enters declarations using extended functions for MR30 This file is automatically created from the configuration file by invoking the configurator include lt mr30 h gt include id h Shown above is an example where mr30 h is placed in the standard directory the directory specified by environment variable INC30 and in h is placed in the current directory The file id h is created in the current directory by invoking the c
63. e of 32 768 to 32 767 as arguments we will create a function add to find a sum of those integers and call it from the main function Prototype declaration void main void long add int int Main function void main void long int answer int a 29 b 40 answer add a b 1 Calls the add function Add function long add int x int y long int Zz 2 Executes addition z longint x y return z 3 Returns a value for the argument rz Flow of data Main function b 40 answer i dummy dummy Add function argument argument Example 1 5 1 Finding sum of integers a function 40 Introduction to C Language 1 1 6 Storage Classes 1 6 Storage Classes 1 6 1 Effective Range of Variables and Functions Variables and functions have different effective ranges depending on their nature e g whether they are used in the entire program or in only one function These effective ranges of variables and functions are called storage classes or scope This section explains the types of storage classes of variables and functions and how to specify them Effective range of variables and functions A C language program consists of multiple source files Furthermore each of these source files consists of multiple functions Therefore a C language program is hierarchically structured as shown in Figure 1 6 1 There are following three storage classes for a variable 1 Ef
64. e task l elalevallde Can be referenced in one task or handler and handler Internal variables Can be referenced in one task or handler Register variables include lt mr30 h gt include id h External variables Can be referenced in all tasks and handlers char mode 0 static variables outside task and handler Can be referenced in static char code 0 tasks and handlers within this file void taski void External variables mode are not initialized when this task is restarted RUN state after being terminated once idle state static char datal s char data2 static variables inside task and handler Can be referenced in the task task1 ete Internal variables Can be referenced in the task task1 for f if mode code 1 data1 code data2 code Figure 3 4 5 Example of reference ranges of variables 146 Using Real time OS MR30 3 3 4 Building MR30 into Program Using NC30 3 4 3 Writing Interrupt Handler Interrupt handlers in MR30 are classified into OS dependent interrupt handlers and OS independent interrupt handlers This section explains how to write OS dependent interrupt handlers and the precautions for writing these handlers Writing OS dependent interrupt handlers in C language System calls i e those usable in OS dependent interrupt handlers can be used in OS dependent interrupt handlers and the specified functions Figure 3 4 6 shows an example of h
65. e the internal labels of a subroutine are registered in a jump table NC30 allows you to change the start address of the subroutine depending on the mode Since multiple processings can be implemented by a single subroutine this method helps to save ROM capacity Determination of mode mode 0 mode gt 2 lt C language source file gt Prototype declaration int clock int int extern int clock mode int void main void int mode int counter 0 mode 2 if mode lt 3 counter clock mode counter clock int m int x int z int p int p clock mode m z p x return Z mode 1 mode 2 Sets return value Stops counting Assembly language source file lt Assembly language source file gt section reset mov w 4ZOFFFFH H1 program count add w 1 R1 stop mov w R1 RO rts section glb clock mode word reset lword count lword stop END rom FE ROMDATA clock mode Registers internal labels of subroutine in jump table Example 2 4 3 A little different way to use table jump 110 ROM ing Technology 2 2 4 Linkage with Assembly Language 2 4 3 Calling C Language from Assembly Language This section explains how to call a C language function from an assembly language program Calling a C language function Follow the rules described below when calling a C language function from an as
66. eceive for user UART1 trance for user UART1 receive for user TIMER AO for user TIMER A1 TIMER A2 TIMER A3 TIMER A4 TIMER BO TIMER B1 TIMER B2 for user vector 28 for user for user for user for user for user for user vector 25 vector 26 vector 27 INTO for user vector 29 INT1 for user vector 30 INT2 for user vector 31 vector 32 for user or MR30 vector 33 vector 34 vector 35 vector 36 vector 37 vector 38 vector 39 vector 40 vector 41 vector 42 gt vector 43 vector 44 vector 45 vector 46 vector 47 to vector 63 from vector 32 is used for MR30 Figure 2 2 11 Setting variable vector table 87 for user or MR30 for user or MR30 for user or MR30 for user or MR30 for user or MR30 for user or MR30 for user or MR30 for user or MR30 for user or MR30 for user or MR30 for user or MR30 for user or MR30 for user or MR30 for user or MR30 for user or MR30 ROM ing Technology 2 2 2 Startup Program Setting the fixed vector table sect30 inc Set the start address of the fixed vector table and the vector address of each interrupt Figure 2 2 12 shows an example of how to write these addresses fixed vector section section fvector fixed vector table Org OFFEOOH still nothing Set the start address of the fixed vector table
67. ecified on function calling side 45 Introduction to C Language 1 1 7 Arrays and Pointers 1 7 Arrays and Pointers 1 7 1 Arrays Arrays and pointers are the characteristic features of the C language This section describes how to use arrays and explains pointers that provide an important means of handling the array What is an array The following explains the functionality of an array by using a program to find the total age of family members as an example The family consists of parents father 29 years old mother 24 years old and a child boy 4 years old See Example 1 7 1 In this program the number of variable names increases as the family grows To cope with this problem the C language uses a concept called an array An array is such that data of the same type int type are handled as one set In this example father s age father mother s age mother and child s age boy all are not handled as separate variables but are handled as an aggregate as family age age Each data constitutes an element of the aggregate Namely the O th element is father the 1st element is mother and the 2nd element is the boy Multiple variables of the gt Array same data type father 29 boy O th element papa mother 4 ist element mama 24 Figure 1 7 1 Concept of an array Example 1 7 1 Finding Total Age of a Family 1 In this example we will find the total age of family members father mo
68. ed Is condition if condition true Is condition u Execution statement A expression if condition expression true Execution Execution statement A statement A Execution else statement A Execution statement B l Execution statement B j Figure 1 4 1 Example for if else statement Example 1 4 1 Count Up if else statement In this example the program counts up a seconds counter second and a minutes counter minute When this program module is called up every 1 second it functions as a clock Declares count up function Refer to Section 1 5 void count up void Functions unsigned int second 0 Declares variables for second seconds counter unsigned int minute 0 and minute m inutes counter void count up void Defines count up function if second gt 59 If greater than 59 seconds second 0 the module resets second and minute counts up minute If less than 59 seconds second the module counts up second ju Example 1 4 1 Count up if else statement 28 Introduction to C Language 1 1 4 Control Statements else if statement Use this statement when it is necessary to divide program flow into three or more flows of processing depending on multiple conditions Write the processing that must be executed when each condition is true in the immediately following block Write the processing that must be executed when none of conditions holds true
69. ed between uppercase and lowercase If the body of a function specified with this pragma command is defined in the C language an error results Be sure to declare the assembler function s prototype before declaring pragma PARAMETER void asm func int int pragma PARAMETER asm func RO R1 void main void Following can be used as register names int i j RO H1 H2 H3 2 ROL ROH R1L R1H asm func i j AO A1 Note however that arguments are passed to a function via these registers Argument i and argument j are stored in RO and H1 respectively when calling a function Figure 2 4 7 Example for writing pragma PARAMETER 105 ROM ing Technology 2 4 Linkage with Assembly Language Calling assembly language subroutine Follow the rules described below when calling an assembly language subroutine from a C language program 1 Write the subroutine in a file separately from the C language program 2 Follow symbol conversion rules for the subroutine name 3 Declare the subroutine s prototype in the C language program from which the subroutine is to be called At this time declare the external reference using the storage class specifer extern C language Assembly language called assembly language section External definition of function s Declaration of argument beginning label symbol glb transfer via register pragma PARAMETER asm func Entry processing of
70. emicolons placed between expressions are left in This for statement and the while statement described above can always be rewritten Expression 1 for expression 11 expression 2 expression 3 Is expression 2 true Execution statement Execution statement Figure 1 4 6 Example for for statement Example 1 4 5 Finding Sum Total 2 for statement In this example the program finds the sum of integers from 1 to 100 Declares sum function void sum void Refer to Section 1 5 Functions unsigned int total 0 Declares the variables used void sum void Defines sum function unsigned int i Defines counter variables for i 1 i 2 100 i Loops until the counter content increments from 1 to 100 Example 1 4 5 Finding sum total 2 for statement 33 Introduction to C Language 1 4 Control Statements do while statement Unlike the for and while statements this statement determines whether a condition is true or false after executing processing post execution determination Although there could be some processing in the for or while statements that is never once executed all processing in a do while statement is executed at least once Execution statement A Execution statement s condition while condition expression expression true Figure 1 4 7 Example for do while statement Example 1 4 6 Finding Sum Total 3 do while statement In this example the
71. endif ifndef identifier If an identifier is not defined NC30 compiles block A if else defined it compiles block B endif In all of these three types the else block can be omitted If classification into three or more blocks is required use elif to add conditions Specifying identifier definition To specify the definition of an identifier use define or NC30 startup option D define identifier lt Specification of definition by define nc30 D identifier lt Specification of definition by startup option 66 Introduction to C Language 1 9 Preprocess Commands Example for conditional compile description Figure 1 9 5 shows an example for using conditional compilation to control incorporation of debug functions define DEBUG It defines an identifier DEBUG Set to debug mode void main void ifdef DEBUG neck outputs When in debug mode it calls debug function otherwise it check output calls ordinary output function In this case it calls debug else function output endif ifdef DEBUG void check output void When in debug mode it incorporates debug function itendif Figure 1 9 5 Example for conditional compile description 67 68 Introduction to C Language 1 9 Preprocess Commands Chapter 2 ROM ing Technology 2 1 Memory Mapping 2 2 Startup Program 2 3 Extended Functions for ROM ing 2 4 Linkage
72. endix C Appendix C Questions amp Answers Reducing generated code 2 lt Question gt Files are divided in our program What points should we consider in order to reduce the generated code Answer Pay attention to the following When referencing data located in SB relative addressing 1 When referencing data located in an SB relative addressing area always be sure to declare pragma SBDATA Source file 1 gt Source file 2 gt Defines mode References mode void func1 void extern void func void char mode extern char mode pragma SBDATA mode pragma SBDATA mode void main void volld func viod mode 1 mode mode 1 funci For mode to be accessed by SB relative declare pragma SBDATA in the referencing program Figure C 2 Example for writing pragma SBDATA For programs whose generated code is 64 Kbytes or less 1 By using the asm function or pragma ASM set DPTJ JMPW JSRW at the beginning of each file which is the branch instruction optimizing control directive command Using asm function Using pragma ASM gt asm OPTJ JMPW JSRW pragma ASM OPTJ JMPW JSRW void funci void oragma ENDASM char mode void funci void void main void Figure C 3 Example for setting OPTJ JMPW JSRW Appedix 14 Date Description Page Summary 12 11 01 Table 1 2 3 is partly revised singned gt signed 65 Explanation of
73. er word dummy int UART1 trance for user word dummy int UART1 receive for user word dummy int TIMER AO for user word dummy int word dummy int word dummy int for user word dummy int TIMER A4 for user vector 25 dummy int TIMER BO for user vector 26 dummy int TIMER B1 for user vector 27 dummy int u INTO for user vector 29 dummy int INT1 for user vector 30 dummy int INT2 for user vector 28 Figure 2 5 6 Example for registering in interrupt vector table 117 ROM ing Technology 2 5 Interrupt Processing 118 Chapter 3 Using Real time OS MR30 3 1 Basics of Real time OS 3 2 Method for Using System Calls 3 3 Development Procedures Using MR30 3 4 Incorporating MR30 by Using NC30 This chapter outlines the functions of the real time OS MR30 for the M16C 60 M16C 20 series and explains the precautions to be observed when you use the real time OS while using NC30 Using Real time OS MR30 3 3 1 Basics of Real time OS 3 1 Basics of Real time OS 3 1 1 Real time OS and Task Programs using a real time OS are configured in units of tasks This section explains how tasks are handled in the real time OS MR30 Programs configured with tasks A task refers to one of program modules that are divided by functionality processing time or other units One task may consist of one function or may be configured with multiple functions MR30 uses different
74. eturn values are valid Only void type arguments are valid No static type functions can be defined as cyclic or alarm handler Only those system calls that are usable in handlers can be used in cyclic and alarm handlers include lt mr30 h gt include id h Only void type return values and arguments are accepted for cyclic handlers No static type functions can be defined as cyclic handlers 5 void cyc hand void iwup tsk ID task1 Figure 3 4 12 Example for writing cyclic handler include lt mr30 h gt Hinclude id h static void cyc hand void No static type functions can be defined as cyclic handler p Figure 3 4 13 Example for writing cyclic handler example of erroneous description Data exchange between cyclic and alarm handlers and tasks When cyclic or alarm handlers exchange data with tasks MR30 uses the same method that is used for exchanging data between OS dependent interrupt handlers and tasks 192 Appendices Appendix A Functional Comparison between NC30 and NC77 Appendix B NC30 Command Reference Appendix C Questions amp Answers l Appendix A Appendix A Functional Comparison between NC30 and NC77 Appendix A Functional Comparison between NC30 and NC77 Regarding sections One noteworthy feature of the M16C 60 M16C 20 series is that they support 1 Mbytes of linear memory space without boundaries every 64 Kbytes and that those banks
75. f how to write such a statement and how it will be expanded Declaration of bit field struct bit char b0 1 char b1 1 E pragma BIT biti Specification to output bit struct bit bit1 instruction struct bit bit2 void main void Expansion image biti b0 1 OOH _bit1 bit2 b0 1 01H _bit2 Figure 2 3 7 Typical description of pragma BIT In addition to the data where pragma BIT is declared the direct 1 bit instruction is generated by the following e Variables where pragma SBDATA is declared e Variables where pragma ADDRESS is declared and that area located at absolute addresses 00000 to 01FFF e near type variables for which the fbit option is specified 95 ROM ing Technology 2 3 Extended Functions for ROM ing Purposes 2 3 3 Control of I O Interface When controlling the I O interface in a built in system specify absolute addresses for variables There are two methods for specifying absolute addresses in NC30 one by using a pointer and one by using an extended function of NC30 This section explains each method of specification Specifying absolute addresses using a pointer Use of a pointer allows you to specify absolute addresses Figure 2 3 8 shows a description example Example Substituting Oxef for address 0000a char point 0000a point char 0x000a point Oxef When rearranged into one ine o9 char 0x000a Oxef Figure 2 3 8 Specifying
76. fective in only a function 2 Effective in only a file 3 Effective in the entire program There are following two storage classes for a function 1 Effective in only a file 2 Effective in the entire program In the C language these storage classes can be specified for each variable and each function Effective utilization of these storage classes makes it possible to protect the variables or functions that have been created or conversely share them among the members of a team otorage classes of variable Storage classes of function 2 Effective File File range 1 1 Figure 1 6 1 Hierarchical structure and storage classes of C language program 41 Introduction to C Language 1 6 Storage Classes 1 6 2 Storage Classes of Variables The storage class of a variable is specified when writing type declaration There are following two points in this 1 External and internal variables location where type declaration is entered 2 Storage class specifier specifier is added to type declaration This section explains how to specify storage classes for variables External and internal variables This is the simplest method to specify the effective range of a variable The variable effective range is determined by a location where its type declaration is entered Variables declared outside a function are called external variables and those declared inside a function are called internal variables External v
77. ferred to as dispatching When the real time OS makes this dispatching the task in the RUN state is suspended This requires that the task s resources e g contents of registers be saved in some place These task resources are called context For the purpose of context management the real time OS prepares as many task control blocks TCBs as the number of tasks set Task Control Block TCB This is a data table that is set for each task managed by the real time monitor Content of TCB Task status Task priority Task 1 Task 2 Area where task s Fa vere Mili stack pointer is section section stored Other D Figure 3 1 3 Main structure of TCB 124 Using Real time OS MR30 3 1 Basics of Real time OS Task dispatch The following shows the flow of task dispatch Dispatch occurs The context of the task in the RUN state is saved to the stack The current stack pointer is saved to an area in the TCB The ID of the next task to be placed in the RUN state is checked Based on this ID a stack pointer is acquired from the TCB of the next task to be placed in the RUN state The context for the next task is acquired from the stack Based on the stack pointer the next task is switched to the RUN state Objects types The items that can be operated on by using a system call are called objects A task itself is part of objects because it can be operated on by a system call Table 3 1 2 lists the objects other t
78. function Saving and setting FB asm func vemm Setting return value Exit processing of function Restoring FB RTS Always write Write if necessary Figure 2 4 8 Calling assembly language subroutine 106 ROM ing Technology 2 2 4 Linkage with Assembly Language Example 2 4 1 Calling Subroutine The program in this example displays count up results using LEDs The LED display part is written in the assembly language and the count up part is written in the C language Then the two parts are linked lt Count up part gt lt LED display part gt ets the method tor Prototype declaration calling assembly P7 equ OSedh Sets the allocated area void led int language function subroutine name glb led Specification of variables used in SB relative addressing pragma SBDATA counter Ide b table a0 P7 static int counter 0 There is no conversion of subroutine name because Mold dale vela pragma PARAMETER is specified if counter lt 9 counter section rom FE ROMDATA j else table counter Q byte OcOh Of9h Oa4h ObOh 099h byte 092h 082h Of8h 080h 090h j led counter Calls assembly language function led end Example 2 4 1 Calling subroutine 107 ROM ing Technology 2 4 Linkage with Assembly Language Calling a subroutine by indirect addressing Normally an instruction jsr is generated for calling an assembly
79. functions are summarized in Table 1 6 2 Table 1 6 1 Storage Classes of Variables Storage i External variable Internal variable class Storage class specifiers omitted Global variables that can also be Variables that are effective in only the referenced from other source files function Allocated in a stack when Allocated in a data area executing the function Variables that are effective in only the function Allocated in a stack when executing the function Local variables that cannot be static referenced from other source files Allocated in a data area Variables that are effective in only the function Allocated in a data area Variables that are effective in only the function Allocated in a register when register executing the function However they do not have any effect in NC30 ignored when compiled Variables that reference variables in other source files cannot be referenced from other functions Not allocated in memory Variables that reference variables in extern other source files Not allocated in memory Table 1 6 2 Storage Classes of Functions Storage class Types of functions Storage class specifiers omitted Global functions that can be called and executed from other source files Specified on function defining side Sate Local functions that can not be called and executed from other source files Specified on function defining side Calls a function in other source files Sp
80. g Example 1 4 3 Switchover of arithmetic operations 2 switch case statement Introduction to C Language 1 4 Control Statements Column Switch case statement without break A switch case statement normally has a break statement entered at the end of each of its execution statements If a block that is not accompanied by a break statement is encountered the program executes the next block after terminating that block In this way blocks are executed sequentially from above Therefore this allows the start position of processing to be changed depending on the value of an expression Determination of expression switch expression Others Constant3 Constant 2 Constant 1 Execution case constant 1 execution statement A statement A Execution case constant 2 execution statement B statement B case constant 3 execution statement C Execution statement C default execution statement D Execution statement D Figure 1 4 4 switch case statement without break 31 Introduction to C Language 1 4 Control Statements 1 4 3 Repetition of Same Processing repeat processing Control statements used to write repeat processing include while for and do while statements This section explains how to write these control statements and shows some examples of usage while statement This statement executes processing in a block repeatedly as long as the given condit
81. g mode when referencing them This makes it possible to generate highly ROM efficient code pragma SBDATA m static int m n void main void j m m 4 n SBSYM m Pseudo instruction SECTION program SBSYM is generated glb _ main for variable m add W Jn m Ms Whether or not to use the SB addressing mode depends on the SECTION bss NE DATA assembler blkb 2 SECTION bss_SE DATA Variable m is located as blkb 2 belonging to the SBDATA attribute end Figure 2 3 5 An image depicting expansion of pragma SBDATA Column Locating both pointer and indicated data in far area What declaration is necessary to locate both a pointer itself and its indicated data in a far area The following shows the format and a description example storage class A type specifier A far A far A variable name Example int far xfar ff data Conversely when locating both in a near area near far specification is unnecessary This is because the variables and pointers in NC30 assume the near attribute by default 93 ROM ing Technology 2 3 Extended Functions for ROM ing Purposes 2 3 2 Handling of Bits NC30 allows the user to handle data in units of bits There are two methods to use data in such a way bit field an application of structs and an extended function of NC30 This section explains each method of use Bit field NC30 supports a bit field as a method to handle bits A bit fiel
82. gma ENDASM to be an area written in the assembly language and outputs it to the assembly language source program directly as it is void func void int E This area is output to the assembly for i 0 i lt 10 i language source program directly as it Is MOV W 0FFH RO FSET i pragma ENDASM Figure 2 3 12 Example for using pragma ASM function Column Suppressing optimization partially by using asm function When the startup option O is added NC30 optimizes generated code when compiling the program However if this optimization causes inconveniences such as when an interrupt occurs NC30 allows you to suppress optimization partially by using the asm function Figure 2 3 13 shows an example for using the asm function for this purpose struct bit char bitO 1 char bit 1 The O option is specified E pragma BIT flag struct bit flag lt Expansion image gt void main void flag bit0 1 Rearranged into 03H _flag i RE one instruction by l flag biti 1 optimization g OOH flag flag bitO 1 dM Optimization is asm omaes 01H flag flag bitt 1 j Figure 2 3 13 Suppressing optimization partially by using asm function 99 ROM ing Technology 2 2 4 Linkage with Assembly Language 2 4 Linkage with Assembly Language 2 4 1 Interface between Functions When the module size is small inline assemble is suff
83. han tasks prepared by MR30 Table 3 1 2 Objects of MR30 Event flag Used to synchronize the timing between tasks The flag can be set one event for one bit 1 word long Used to synchronize the timing between tasks A semaphore is used Semaphore mainly for exclusive control between tasks Exclusive control by semaphore is based on a semaphore counter Mail box Used to communicate exchange data between tasks One word long data or start address of data block can be sent to and from a mail box A counter though not an object is provided inside the TCB to synchronize the timing of operation between tasks Each object is managed by an identification number ID as for tasks The ID can be any value set by the user Column Some note about scheduling In addition to the priority method there are following methods of scheduling e FCFS method First Come First Service Tasks are switched to the RUN state in the order they go to a READY state e Round robin method Tasks are switched to the RUN state sequentially in the same way as with the FCFS method The difference is that a task in the RUN state is forcibly switched to another at certain time intervals by the real time OS 125 Object management Using Real time OS MR30 3 1 Basics of Real time OS The real time OS uses a system call to manage the objects Table 3 1 3 lists the system calls necessary to manipulate tasks and each object and their functions Tabl
84. his provides an effective means of using definitions in common to eliminate magic numbers immediates with unknown meanings in the program define THRESHOLD 100 define UPPER LIMIT THRESHOLD 50 Sets the upper limit at 50 define LOWER LIMIT THRESHOLD 50 Figure 1 9 2 Example for defining a constant Defining a character string It is possible to assign a character string a name or conversely delete a character string define TITLE Position control program The defined character string is inserted at the position of TITLE char mess TITLE define void void is deleted For a compiler where void is not supported this definition void func eliminates the need for modification in the source file j Figure 1 9 3 Example for defining a character string 64 Introduction to C Language 1 9 Preprocess Commands Defining a macro function The command define can also be used to define a macro function This macro function allows arguments and return values to be exchanged in the same way as with ordinary functions Furthermore since this function does not have the entry and exit processing that exists in ordinary functions it is executed at higher speed What s more a macro function does not require declaring the argument s data type Macro function that returns the argument s absolute value define ABS a a 0 a a p fin EQN a b c m de x SEQ i The symbol
85. ht be executed first Table 1 3 13 Operator Priorities Hules of Type of operator Operator a combination Expression PLE a Note 2 Note 3 amp Monadic arithmetic operators etc sizeof type Note 4 Multiply divide operators Add subtract operators Shift operator Relational operator comparison Relational operator equivalent Bitwise operator AND Bitwise operator EOR Bitwise operator OR Logical operator AND Logical operator OR TI LI bid T e s tT Conditional operator Assignment operator T Comma operator l Note 1 The dot denotes a member operator that specifies struct and union members Note 2 The asterisk denotes a pointer operator that indicates a pointer variable Note 3 The ampersand amp denotes an address operator that indicates the address of a variable Note 4 The asterisk denotes a multiply operator that indicates multiplication 26 Introduction to C Language 1 1 4 Control Statements 1 4 Control Statements 1 4 4 Structuring of Program The C language allows all of sequential processing branch processing and repeat processing the basics of structured programming to be written using control statements Consequently all programs written in the C language are structured This is why the flow of processing in C language programs are easy to understand This section describes how to write these co
86. iable Declaring a pointer variable The format show below is used to declare a pointer variable Pointed data type pointer variable name However it is only an area to store an address that is allocated in memory by the above declaration For the data proper to be assigned an area it is necessary to write type declaration separately Pointer variable declaration p p p Address Address Address char type No area is allocated PET type Figure 1 7 4 Pointer variable declaration and memory mapping 49 Introduction to C Language 1 1 7 Arrays and Pointers Relationship between pointers and variables The following explains the relationship between pointer variables and variables by using a method for substituting constant 5 by using pointer variable p for variable of int type a as an example void main void int a int p postes modifier p amp a This amp a indicates the address of p 5 variable a This p indicates the content of variable a Figure 1 7 5 Relationship between pointer variables and variables Column Data length of pointer variable The data length of variables in C language programs are determined by the data type For a pointer variable since its content is an address the data length provided for it is sufficiently large to represent the entire address space that can be accessed by the microprocessor used Pointer variables in NC30 are two or four bytes i
87. iable that is defined in another file like mode in source file 2 of Figure 1 6 3 Source file 1 Source file 2 Memory space char mode extern char mode Program Common mode static int count static int count area count of source void func1 void void func2 void file 1 mode STOP mode BACK count 0 count 100 count of source file 2 Figure 1 6 3 Storage classes of external variable Storage classes of internal variable An internal variable declared without adding any storage class specifier has its area allocated in a stack Therefore such a variable is initialized each time the function is called On the other hand an internal variable whose storage class is specified to be static is allocated in a data area In this case therefore the variable is initialized only once when starting up the program Source file void funci void Fi EUM i Memory space char flag 0 P count of func static int count 0 Program area rs flag SET count of func2 func2 Stack area C void func2 void ZEE GEN flag of func2 char flag 2 0 B static int count 0 Return flag SET j address count count 1 v flag of func1 Figure 1 6 4 Storage classes of internal variable 43 Introduction to C Language 1 6 Storage Classes 1 6 3 Storage Classes of Functions The storage class of a function is specified on both function defining and function calling sides The st
88. ial setup program for the peripheral I Os used Figure 3 3 4 Initializing peripheral I Os 137 Using Real time OS MR30 3 3 3 Development Procedures Using MR30 Modification of memory map c sec inc Set the start address of each section by using a pseudo instruction org Sections without specified start addresses are located at contiguous addresses following the previously defined section Set the start address of each area according to the memory map data SE top sectionbss SE DATA ALIGN bss SE top section data FE DATA Org 0000H data FE top section rom FE ROMDATA Org OFOOOOH rom_FE_top Figure 3 3 5 Modifying memory map 138 Using Real time OS MR30 3 3 3 Development Procedures Using MR30 Object definition file configuration file Write the definition of each object in a file called configuration file Create this configuration file from the template file default cfg for configuration files provided by MR30 real time monitor Task ID task priority task stack size etc Define each object Event flag semaphore mail box memory pool Define cyclic handler Define alarm handler Define interrupt handler etc etc Figure 3 3 6 Outline of configuration file The created configuration file is expanded into a file by the configurator cfg30 provided by MR30 the file that is required when building MR30 into the system Column Mem
89. icient to solve the problem However if the module size is large or when using an existing module in the program NC30 allows you to call an assembly language subroutine from the C language program or vice versa This section explains interfacing between functions in NC30 Entry and exit processing of functions The following lists the three primary processings performed in NC30 when calling a function 1 Construct and free stack frame 2 Transfer argument 3 Transfer return value Figure 2 4 1 shows a procedure for these operations int func int int int func int x int y void main void j int a 3 b 5 Es c func a b Public declaration of label Preparation for func passing argument Constructing stack frame JSR func Receiving return value Receiving argument Storing return value Freeing stack frame including RTS Figure 2 4 1 Operations for calling a function 100 ROM ing Technology 2 2 4 Linkage with Assembly Language Structure of a stack frame When a function is called an area like the one shown below is created in a stack This area is called a stack frame The stack frame is freed when control returns from the called function Area for saving registers Area allocated by the Automatic variable area called function Old frame pointer Return address Area allocated by the calling function Argument area Figure 2 4 2 Structure of a stack frame Cons
90. identification numbers ID for each task for the purpose of task management The task ID can be any desired value Task 3 Figure 3 1 1 Program configuration with multiple tasks Task styles Each task assumes one of the styles listed in Table 3 1 1 Table 3 1 1 Task Styles void task1 void void task void void task3 void for for 121 Using Real time OS MR30 3 3 1 Basics of Real time OS Task status All tasks are managed by the real time OS The real time OS refers to a system call a request from each task to determine the task to be executed The status of each task also is managed by the real time OS Figure 3 1 2 shows task status in MR30 Gains control of the CPU eg Relinquishes control of the CPU READY Executable state RUN Executing state Task places itself in wait state WAIT Idle state Clears wait state Request from Request from other other task to clear task for forced wait forced wait WAIT SUSPEND Forced idle state Request from other task for forced termination Request from other task for forced wait Request to clear wait state SUSPEND Forced idle state Request to clear forced wait Request from other task for forced termination DORMANT Idle state Invocation from other task Figure 3 1 2 Each task status including status transit
91. ility for the interrupt that needs to be invoked in the shortest time possible pragma INTERRUPT B intr section program glb intr void intr void ERE intr Malt dd fset B Interrupt processing Interrupt processing Returns to register bank O Returns by reit instruction Figure 2 5 2 An image depicting expansion of fast interrupt processing function Note When not using multiple interrupts this facility can be used in all interrupts 113 ROM ing Technology 2 2 5 Interrupt Processing Writing software interrupts pragma INTCALL To use the M16C software interrupts write a command statement as follows pragma A INTCALL A INT number A function name In software interrupts arguments can be passed to a function via registers Furthermore any return value except those expressed by a struct or union can be received from the called function Be sure to declare the function prototype before declaring pragma INTCALL void call32 int int INT number decimal pragma INCALL 32 call32 RO H1 Following can be used as register names RO R1 R2 R3 ROL ROH R1L R1H void main void AO A1 These arguments are passed to a function via these registers int m n call32 m n Function CALL32 is called by INT instruction enter 02H Sets argument in register mov w 2 FB R1 mov w 2 FB RO Figure 2 5 3 Example for writing Zpragma INTCALL 114 ROM ing Technology 2 2 5
92. in the last else block Is condition if condition expression 1 expression 1 true Execution statement A if ndition expression 2 Is condition else cond p expression 2 true ee ecuion Execution statement B statement B i else if condition expression 3 Is condition expression 3 true Execution statement C Execution statement C Execution else statement D Execution statement D Figure 1 4 2 Example for else if statement Example 1 4 2 Switchover of Arithmetic Operations 1 else if statement In this example the program switches over the operation to be executed depending on the content of the input data sw void select void Declares select function Refer to Section 1 5 Functions int a2 29 b 40 long int ans char sw Declares the variables used void select void Defines select function if sw 0 A If the content of sw is 0 ans a bD the program adds data else if sw 1 If the content of sw is 1 ans a b the program subtracts data Bi eise It SW If the content of sw is 2 ans a b the program multiplies data If the content of sw is 3 the program divides data If the content of sw is 4 or greater the program performs error processing Example 1 4 2 Switchover of arithmetic operations 1 else if statement 29 Introduction to C Language 1 1 4 Control Statements switch case statement This statement causes progra
93. ion expression is met An endless loop can be implemented by writing a constant other than O in the condition expression because the condition expression in this case is always true Is condition while expression Hi j p condition expression Execution statement A Execution statement A Figure 1 4 5 Example for while statement Example 1 4 4 Finding Sum Total 1 while statement In this example the program finds the sum of integers from 1 to 100 Declares sum function Refer to Section 1 5 void sum void Functions unsigned int total O Declares the variables used void sum void Defines sum function unsigned int i 1 Defines and initializes counter variables while i lt 1 00 Loops until the counter content reaches 100 total i Changes the counter content Example 1 4 4 Finding sum total 1 while statement 32 Introduction to C Language 1 4 Control Statements for statement The repeat processing that is performed by using a counter like in Example 1 4 4 always requires operations to initialize and change the counter content in addition to determining the given condition A for statement makes it possible to write these operations along with a condition expression See Figure 1 4 6 Initialization expression 1 condition expression expression 2 and processing expression 3 each can be omitted However when any of these expressions is omitted make sure the s
94. ions Especially important among the above states are RUN READY and WAIT This is a state where processing in the task can be executed Only one task at a time can be in this state This is a state where the task is waiting to be placed in the RUN state When a task in the RUN state changes state one of the tasks in the READY state enters the RUN state This is a state where a task in the RUN state has had its processing stopped by some cause When a task in the RUN state goes idle the real time OS places one of the tasks in the READY state into a RUN state 122 Using Real time OS MR30 3 3 1 Basics of Real time OS Changeover of task status There are following three events upon which tasks change state e When the RUN task has issued a system call When a system call is issued in an interrupt program e When a system call is issued in the interrupt program managed by the real time OS Thus tasks are made to change state by issuing a system call and the task in the RUN state is changed from one task to another in succession Then when a wait time occurs in the program the real time OS executes another processing that is irrelevant to the wait Column MR30 and ulTRON specifications MR30 is the real time OS based on uITRON specifications The uITRON specifications are industry standards created in Japan for real time OSs that are designed specifically for controlling microcompu
95. is generated as user macro int func int int int func int x int y i return x y mov w R1 RQ j void main void int m n int ans There must be a body definition before a function call within the same file ans func m n Figure 2 4 6 Example for writing inline storage class 104 ROM ing Technology 2 2 4 Linkage with Assembly Language 2 4 2 Calling Assembly Language from C Language This section explains details on how to write command statements for calling an assembly language subroutine as a C language function Passing arguments to assembly language pragma PARAMETER pragma PARAMETER function name register name A function that is written as shown above sets arguments in specified registers without following the ordinary transfer rules as it performs call up operation Use of this facility helps to reduce the overhead during function call because it does not require stack manipulation for argument transfers However the following precautions must be observed when using this facility 1 Before writing pragma PARAMETER be sure to prototype declare the specified function 2 Observe the following in prototype declaration e Make sure a function arguments are an 8 bit or 16 bit integer or a 16 bit pointer Structs and unions cannot be declared as a function return value Make sure the register sizes and argument sizes are matched Register names are not discriminat
96. k trace function greg Outputs debug information about register variables Appedix 7 l Appendix B Appendix B NC30 Command Reference Alarm options Table B 5 Alarm Options Abbreviation Outputs alarm when attempt is made to use or Wnon prototype define the function whose prototype is not declared Outputs alarm when mpt is m Wunknown pragma WUP p when attempt is made to use unsupported Zpragma Does not stop compile operation even when error occurs Outputs error message to host com r Wstdout None P 9 pail standard output device stdout Optimization options Table B 6 Optimization Options Abbreviation Optimizes to minimize both speed and None ROM size oR None Optimizes by emphasizing ROM size than speed OS None pune by emphasizing speed than ROM size order S 1 1 E h ff Ono_break_source_debug ONBSD BP Pieoee Gui avo Miareecr source line information Optimizes to remove stack correction de This hel ROM size Osp adiust OSA code elps to binos OM size However it could result in increased stack amount Suppresses inline embedding of standard Ono stdlib ONS library functions or modification of library functions Suppresses optimization th n ese ONC pp p ation that deletes common instructions Appedix 8 l Appendix B Appendix B NC30 Command Reference Library specifying options Table B 7 Library Specifying Options lA lt li
97. language subroutine from the C language To call a subroutine by indirect addressing using jsri use a function pointer However when using a function pointer note that no registers can be specified for argument transfers by pragma PARAMETER Figure 2 4 9 shows a description example Assembly language source file Be sure to declare the called subroutine as an external referenced function in advance ExtemaldasetaratiomroteledeubrOUHS C language source file gt Assembly language source file gt Prototype declaration extern int count up int extern int count down int section program glb count_up count_up add w 1H R1 void main void Declares function mov w R1 RO pointer int counter 2 0 us int mode int jump adr int glb count down sub w 1 R1 mov w R1 RO rts count down if mode 0 jump_adr count up Sets jump address in function pointer else jump_adr count_down end Arguments and return values are exchanged following NC30 s counter jump adr Counter transfer rules Figure 2 4 9 Calling a subroutine by indirect addressing 108 ROM ing Technology 2 4 Linkage with Assembly Language Example 2 4 2 Calling a Subroutine by Table Jump The program in this example calls different subroutines from a C language program according to the
98. le using NC30 the C compiler for the M16C 60 M16C 20 series This manual will prove helpful to you as a guide to the C language as well as a textbook to be referenced when creating a C language program For details about hardware and development support tools available for each type of microcomputer in the M16C 60 M16C 20 series please refer to the user s manual and instruction or reference manuals supplied with your microcomputer Chapter 1 Introduction to C Language ed Chapter 2 ROM ing Technology 8S O Chapter 3 Using Real time OS MR30 8 o Appendices L Ajip em dle es Guide to Using This Manual This manual is a programming manual for NC30 the C compiler for the M16C 60 M16C 20 series Knowledge of the M16C 60 M16C 20 series microcomputer architecture and the assembly language is required before using this manual This manual consists of three chapters The following provides an approximate guide to using this manual e Those who learn the C language for the first time Begin with Chapter 1 e Those who wish to know NC30 extended functions Begin with Chapter 2 e Those who use the real time OS MR30 Begin with Chapter 3 Furthermore appendices are included at the end of this manual Functional Comparison between NC30 and NC77 nc30 Command Reference and Q amp A M16C Family related document list Usages Microcomputer development flow Selection of Type of document C
99. ll parameters Write the parameters for a system call as arguments of a function Include file required for using MR30 include lt mr30 h gt eee ee Include file required for manipulatin void task void ae pus objects wup tsk ID task1 Activates a task READY state Figure 3 2 3 Writing a system call which has parameters Object specification When using system calls in MR30 that manipulate objects specify the ID of the object In MR30 an object name is used for this ID to indicate it in a visually understandable manner Although a simple numeric value can be used to specify the ID Mitsubishi recommends using this method for better readability of the program Method for specifying ID ID object name Set any object name as desired 132 Using Real time OS MR30 3 3 2 Method for Using System Calls Error code of system calls All return values of system calls constitute the error codes of system calls Specific character strings are used for these error codes also for easy identification Table 3 2 1 lists the error codes of system calls Table 3 2 1 Error Code List E RLWAI Wait state forcibly cleared These error codes can be used to choose the processing to be performed after using a system call Figure 3 2 4 shows an example for using error codes for this purpose l Include file that is required by using MR30 include lt mr30 h void task void In MR30 arbitrary characters are u
100. m flow to branch to one of multiple processing depending on the result of a given expression Since the result of an expression is handled as a constant when making decision no relational operators etc can be used in this statement switch expression Constant 1 Constant 2 Constant3 Others case constant 1 execution statement A break case constant 2 execution statement B break case constant 3 execution statement C Execution statement C break default execution statement D statement D break Figure 1 4 3 Example for switch case statement Example 1 4 3 Switchover of Arithmetic Operations 2 switch case statement In this example the program switches over the operation to be executed depending on the content of the input data sw Declares select function void select void Refer to Section 1 5 Functions int a229 b240 Declares the variables used long int ans char sw void select void Defines select function switch sw Determines the content of sw case 0 ans a b 4 If the content of sw is 0 the program break adds data case 1 ans a b If the content of sw is 1 the program break subtracts data case 2 ans a b If the content of sw is 2 the program break multiplies data case 3 ans a b x If the content of sw is 3 the program break divides data default error If the content of sw is 4 or greater the break program performs error processin
101. memory management functions In this case it is possible to prevent unwanted libraries from being linked and reduce ROM sizes by turning lines of statements initializing the heap area in ncrt0 a30 into comments When not using memory management functions set 0 and glb mbase turn the heap area initialization glb _mnext glb msize section into comments mov w heap top amp OFFFFH mbase mov w mov w heap top amp OFFFFH mnext mov w heap_top gt gt 16 mnext 2 mov w heap top amp OFFFFH msize mov w heap_top gt gt 16 msize 2 Figure 2 2 6 Setting the heap area Setting the size of stack area ncrt0 a30 By using the results obtained by the stack size calculating utility stk30 etc set the user stack and the interrupt stack sizes When using multiple interrupts find the total size of interrupt stacks used for them and set it as the interrupt stack size J J J When using multiple interrupts set the total size of interrupt stacks used for them Figure 2 2 7 Setting the stack size 84 ROM ing Technology 2 2 2 Startup Program Setting the start address of interrupt vector table ncrt0 a30 Set the start address of the interrupt vector table The value set here is set in the interrupt table register INTB within ncrt0 a30 VECTOR ADR equ OFFDOOH Set in interrupt table register INTB interrupt section start glb start section interrupt start J after reset this p
102. n conformity with memory SBDATA area section data SE top section bss SE DATA bss E top section data FE DATA Org 10000H data FE top section rom FE ROMDATA Ore OFOOOOH data_FE_top Figure 2 2 10 Setting the start address of each section 86 Setting the variable vector table sect30 inc ROM ing Technology 2 2 Startup Program Add the setup items related to the variable vector table to the section definition file Sect30 inc Figure 2 2 11 shows an example of how to set section org lword org lword lword lword lword org lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword lword VECTOR ADR dummy int VECTOR ADR 44 dummy int dummy int dummy int dummy int VECTOR ADR 63 dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int dummy int variable vector table vector 0 BRK DMAO for user DMA1 for user input key for user AD Convert for user UARTO trance for user UARTO r
103. n data length depending on the location near or far area where the corresponding data is stored For details about this refer to Section 2 1 Memory Mapping 50 Introduction to C Language 1 7 Arrays and Pointers 1 7 4 Using Pointers This section shows some examples for effectively using a pointer Pointer variables and one dimensional array When an array is declared by using subscripts to indicate its element numbers it is encoded as index addressing In this case therefore address calculations to determine each address as reckoned from the start address are required whenever accessing the array On the other hand if an array is declared by using pointer variables it can be accessed in indirect addressing void main void str 0 or p Str 1 or p 1 char str ab 042 char p str 1 or p 2 char t p sStr t p 1 The start address of a one dimensional array can be obtained by sir Address modifier amp is unnecessary Figure 1 7 6 Pointer variables and one dimensional array Pointer variables and two dimensional array As in the case of a one dimensional array a two dimensional array can also be accessed by using pointer variables void main void mtx 0 0 har mtx 2 3 1 io char mtx ab cd mtx 0 2 l mtx 1 0 or p char p mtx 1 1 or p 1 char t mtx 1 2 or p 2 p mtx 1 t2 p 1 The start address of the first row of a two
104. names 73 ROM ing Technology 2 1 Memory Mapping 2 1 3 Control of Memory Mapping NC30 provides extended functions that enable memory mapping to be performed in an efficient way to suit the user s system This section explains NC30 s extended functions useful for memory mapping Changing section names pragma SECTION pragma A SECTION A designated section base name A changed section base name This function changes section base names generated by NC30 The effective range of a changed name varies between cases when program is changed and when some other section base name is changed For data For program int data1 prog void func1 void EGCHOn name Expanded in default section name j changed pragma SECTION data new data pragma SECTION program new progra int data2 void func2 void Expanded in changed section name For both expanded in changed section name section section new_program section new data NO DATA blkb 2 blkb 2 Figure 2 1 5 Typical description of pragma SECTION 74 ROM ing Technology 2 2 1 Memory Mapping Forcible mapping into ROM const modifier Both RAM and ROM areas are allocated by writing the initial data when declaring the type of a variable However if this data is a fixed data that does not change during program execution write the const modifier when declaring the type Because only a ROM area is allocated and no RAM a
105. nation when used in a for statement e When used in a while statement When used in a for statement Expression 1 Is condition expression Is expression 2 true true Execution statement Execution statement Figure 1 4 9 Example for continue statement 35 Introduction to C Language 1 4 Control Statements goto statement When a goto statement is executed the program unconditionally branches to the label written after the goto statement Unlike break and continue statements this statement makes it possible to exit multiple blocks collectively and branch to any desired location in the function See Figure 1 4 10 However since this operation is contrary to structured programming it is recommended that a goto statement be used in only exceptional cases as in error processing Note also that the label indicating a jump address must always be followed by an execution statement If no operation need to be performed write a dummy statement only a semicolon after the label void main void _while 1 goto err err errorf Entering a label label execution statement If no operation need to be performed label dummy statement Figure 1 4 10 Working of goto statement 36 Introduction to C Language 1 1 5 Functions 1 5 Functions 1 5 4 Functions and Subroutines As subroutines are the basic units of program in the assembly language so are the functions in the C language This secti
106. nformation contained herein Mitsubishi Electric Corporation semiconductors are not designed or manufactured for use in a device or system that is used under circumstances in which human life is potentially at stake Please contact Mitsubishi Electric Corporation or an authorized Mitsubishi Semicon ductor product distributor when considering the use of a product contained herein for any specific purposes such as apparatus or systems for transportation vehicular medical aerospace nuclear or undersea repeater use The prior written approval of Mitsubishi Electric Corporation is necessary to reprint or repro duce in whole or in part these materials If these products or technologies are subject to the Japanese export control restrictions they must be exported under a license from the Japanese government and cannot be im ported into a country other than the approved destination Any diversion or reexport contrary to the export control laws and regulations of Japan and or the country of destination is prohibited Please contact Mitsubishi Electric Corporation or an authorized Mitsubishi Semiconductor product distributor for further details on these materials or the products contained therein Preface This programming manual is written about the M16C 60 M16C 20 series of Mitsubishi CMOS 16 bit microcomputers explaining the basics of the C language and describing how to put your program into ROM and how to use the real time OS MR30 whi
107. nguage asm function asm character string When the above line is entered the character string enclosed with double quotations is expanded directly including spaces and tabs into the assembly language source program Since this line can be written both in and outside a function it will prove useful when one wishes to manipulate flags and registers directly or when high speed processing is required Figure 2 3 10 shows a description example void main void niae Sets interrupt enable flag Figure 2 3 10 Typical description of asm function Accessing automatic variables in assembly language asm function When it is necessary to access automatic variables inside the function write a statement using FB as shown in Figure 2 3 11 Since the compiler replaces with the FB register s offset value automatic variable names in the C language can be used in assembly language programs void main void unsigned int m FB relative addressing is used lt Format gt asm assembly language automatic variable name exitd Figure 2 3 11 Using automatic variables in asm function 98 ROM ing Technology 2 3 Extended Functions for ROM ing Purposes Writing entire module in assembly language pragma ASM If the embedded assembly language consists of multiple lines use an extended function oragma ASM With this extended function NC30 determines a section enclosed with oragma ASM and pra
108. nted before assignment b a gt a a 1 b a Postfix type The value is incremented or decremented after assignment b a gt b a ja a 1 Binary arithmetic operators In addition to ordinary arithmetic operations these operators make it possible to obtain the remainder of an integer divided by integer operation Table 1 3 3 Binary Arithmetic Operators l l Returns the sum of expression 1 and expression 1 expression 2 l l l expression 2 after adding their values l l Returns the difference between expressions 1 expression 1 expression 2 l l and 2 after subtracting their values l l Returns the product of expressions 1 and 2 expression 1 expression 2 m after multiplying their values Returns the quotient of expression 1 after diving expression 1 expression 2 its value by that of expression 2 Returns the remainder of expression 1 after expression 1 96 expression 2 dividing its value by that of expression 2 Introduction to C Language 1 3 Operators Assignment operators The operation of expression 1 expression 2 assigns the value of expression 2 for expression 1 The assignment operator can be used in combination with arithmetic operators described above or bitwise or shift operators that will be described later This is called a compound assignment operator In this case the assignment operator must always be written on the right side of the equation Table 1 3 4 Substitute Operators
109. ntroduction to C Language 1 3 Operators Cast operator When operation is performed on data whose types differ from each other the data used in that operation are implicitly converted into the data type that is largest in the expression However since this could cause an unexpected fault a cast operator is used to perform type conversions explicitly Table 1 3 11 Cast Operator h f th i new data type variable Converts the data type of the variable to the new data type Comma operator This operator executes expression 1 and expression 2 sequentially from left to right This operator therefore is used when enumerating processing of short descriptions Table 1 3 12 Comma operator Executes expression 1 and expression 2 expression 1 expression 2 l l sequentially from left to right 25 Introduction to C Language 1 1 3 Operators 1 3 6 Priorities of Operators The operators used in the C language are subject to priority resolution and rules of combination as are the operators used in mathematics This section explains priorities of the operators and the rules of combination they must follow Priority resolution and rules of combination When multiple operators are included in one expression operation is always performed in order of operator priorities beginning with the highest priority operator When multiple operators of the same priority exist the rules of combination specify which operator left or rig
110. ntrol statements and shows some examples of usage Structuring of program The most important point in making a program easy to understand is how the program flow can be made easily readable This requires preventing the program flow from being directed freely as one wishes Thus a move arose to limit it to the three primary forms sequential processing branch processing and repeat processing The result is the technique known as structured programming Table 1 4 1 shows the three basic forms of structured programming Table 1 4 1 The three basic forms of structured programming Sequential Executed top down from processing top to bottom PR False ondition Branched to processing A or processing B Branch depending on whether processing Processing B condition P is true or false Processing A is repeated Repeat as long as condition P is processing Processing A met ef Introduction to C Language 1 4 Control Statements 1 4 2 Branching Processing Depending on Condition branch processin Control statements used to write branch processing include if else else if and switch case statements This section explains how to write these control statements and shows some examples of usage if else statement This statement executes the next block if the given condition is true or the else block if the condition is false Specification of an else block can be omitted e f the else statement is omitt
111. on explains how to write functions in NC30 Arguments and return values Data exchanges between functions are accomplished by using arguments equivalent to input variables in a subroutine and return values equivalent to output variables in a subroutine In the assembly language no restrictions are imposed on the number of input or output variables In the C language however there is a rule that one return value per function is accepted and a return statement is used to return the value No restrictions are imposed on arguments ots e Subroutine in assembly language Main routine Subroutine Input variable 1 Input variable 2 JSR SUB Output variable 1 Output variable 2 SUB END RTS e Function in C language Main function calling function Function called function Argument 1 Argument 2 Return value One value per return return value function Figure 1 5 1 Subroutine vs function Note In some compilers designed for writing a finished program into ROM the number of arguments is limited 3 Introduction to C Language 1 5 Functions 1 5 2 Creating Functions Three procedures are required before a function can be used These are function declaration prototype declaration function definition and function call This section explains how to write these procedures Function declaration prototype declaration Before a function can be used in the C language function
112. on to the Call by Value and the Call by Reference methods there is another method to pass data to and from functions With this method the data to be passed is turned into an external variable This method results in loosing the independency of functions and hence is not recommended for use in C language programs Yet it has the advantage that functions can be called at high speed because entry and exit processing argument and return value transfers normally required when calling a function are unnecessary Therefore this method is frequently used in ROM ed programs where general purpose capability is not an important requirement and the primary concern is high speed processing 52 Introduction to C Language 1 1 7 Arrays and Pointers 1 7 5 Placing Pointers into an Array This section explains a pointer array where pointer variables are arranged in an array Pointer array declaration The following shows how to declare a pointer array Data type far 9 x array name number of elements Pointer array declaration 1 char far ptr1 3 ptr1 0 char type data int far ptr2 3 ptr1 1 char type data ptr1 2 char type data ptr2 0 int type data ptr2 1 int type data int type data Pointer array initialization ptbi O T p spa ptbl 1 START es reser ssas s r w w v w RESTART ptbi 2 wisai wp e s e v w ptbl 3 esr s eT Er Te n To Each character string s start address is stored here Figure 1 7
113. onfigurator 141 Using Real time OS MR30 3 4 Building MR30 into Program Using NC30 Extended functions for MR30 The extended functions provided for MR30 use the pragma commands which are the preprocess commands of NC30 These extended functions must be written in places preceding the functions to be specified Table 3 4 2 lists the extended functions provided for MR30 Table 3 4 2 Extended Commands for MR30 Extended command Meaning pragma TASK Specifies the function that serves as a task Specifies the function that serves as an OS dependent interrupt pragma INTHANDLER handler pragma HANDLER Abbreviated form of INTHANDLER pragma CYCHANDLER Specifies the function that serves as a cyclic handler pragma ALMHANDLER Specifies the function that serves as an alarm handler However the required extended functions for MR30 are automatically built in by using MR30 s configurator Therefore there is no need to write these extended commands 142 Using Real time OS MR30 3 3 4 Building MR30 into Program Using NC30 3 4 2 Writing Tasks using NC30 This section explains how to write tasks using NC30 and the precautions to be observed when writing tasks Method for writing tasks MR30 system calls can be used in the function specified in a task and in the function that is called by that function Figure 3 4 1 shows an example for writing a task include lt mr30 h gt include id h void taski
114. ons sees 41 1 6 2 Storage Classes of Variables uses totne ttes oet otra tuti essa Su see o bu laste utes shes busti st Es MUR ORSUN su beepEUbE 42 1 6 3 Storage Classes of Functions sseessssssssssssssssessseeene nennen nnne nnne nnns nnn nnns 44 1 7 Arrays and de iii sussana EEE A EEA 46 DEAE us a E E a a tines 46 Desh SUMING VMN seiskas E E E E E NE 47 kro FONE ao mm 49 NEM FONO cini mmm 51 Let gt Placing Pointers into an Aray asseemapriesubeurinumciagersaccex a Eana R EENEN a EEEE AEAEE ERNER Pia FPEM Ear d 53 1 7 6 Table Jump Using Function Pointer cvcccsdacordesssance vavececestecaceaqesnntoacuettsspesedetheeosaeneteienersosacanctes 55 1 8 Struct and Unio pm ERE 57 TSI Struct and UMON seirinin T m mm 57 1 8 2 Creating New Data Types ERE TT m TIT 58 1 9 Preprocess CommandsS s nssnnunnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnmnnn nnn nnnnnn mnnn 62 1 9 1 Preprocess Commands of NGS siccccccsstinzspuccinmnaseariiclenantenedcapenseseteusdbneiiedesaiiidnenecleodaaiansewese 62 UE P We aerarium 63 Wo Macro DEINO esirin IC ms 64 1 9 4 Conditional Compile ellssssseeeeeisesseeee enne nnne nnn nna nnns nns nn aa anser sinas aiiis 66 Chapter 2 ROM ing Technology 21T Memory Mapping et 71 2 Alek Iypes oi code Foi m 71 2 1 2 Sections Managed Dy NGS icai rator reete t a hp feeewsasasvennsvesssba
115. ontents Hardware specifications pin assignment memory map specifications of peripheral microcomputer i Data sheet and data book feb l m b functions electrical characteristics timin Outline design S charts of system i5 Detailed description about hardware specifi I User s manual cations operation and application examples Detail design connection with peripherals relationship of system with software D Method for creating programs using assem Hard S manual bly and C languages ware gt Software manual Detailed description about operation of each devel D instruction assembly language opment System evaluation M16C Family Line up M16C Family M16C 80 Series M16C 80 Group M16C 60 Series M16C 60 Group M16C 61 Group M16C 62 Group M16C 20 Series M160C 20 Group M16C 21 Group Table of contents Chapter 1 Introduction to C Language 1 1 Programming in C Language cerei anoxumau neue usd P RE Gpb ua eR Ed n utuiicu ao sauna ou nua cafe cu sana cu noa RR nnmnnn 3 1 1 1 Assembly Language and C Language uot En nte REX uum RO Td une oU Kx a utc ix uad Xn Iesi n ae 3 1 2 Program Development Proc adUre usvceenvtieiaceutipitetvusebabdEL ena richest tcierdscavnerieoeniiaarmanetervichans 4 1 1 3 Easily Understandable Program cccccssssccccssececceeeeeeeceeeeeeeeauececeseeeeesseaeeeeseuauseeesageeeeseas 6 12 Ae YPES qt
116. or ROM ing Purposes near far of pointers By specifying near far for a pointer it is possible to specify the size of addresses stored in the pointer and an area where to locate the pointer itself If nothing is specified all pointers are handled as belonging to the near attribute 1 Specify the size of addresses stored in the pointer storage class A type specifier A near far A variable name near 16 bits long 16 bit absolute far 20 bits long 20 bit absolute Figure 2 3 3 Specifying address size stored in pointer 2 Specify the area in which to locate the pointer itself storage class A type specifier A near far A variable name near Located in near area far Located in far area near datal int near near data int far far data NE uM near area 7 mear daa E sfar_data o far_data ERES far area Figure 2 3 4 Specifying area to locate the pointer near far of functions The attributes of NC30 functions are fixed to the far area for reasons of the M16C 60 M160C 20 series architecture If near is specified for an NC30 function NC30 outputs a warning when compiling the program and forcibly locates it in the far area 92 ROM ing Technology 2 2 3 Extended Functions for ROM ing Purposes Using SB relative addressing pragma SBDATA pragma SBDATA variable name For the variables declared in this way NC30 generates AS30 pseudo instruction SBSYM and uses the SB relative addressin
117. or current directory include file name This statement takes in a file from the current directory If the specified file does not exist in the current directory NC30 searches the directory specified with the startup option l and the directory set with NC30 s environment variable INC30 in that order as it takes in the file To discriminate your original include file from the standard include file place that file in the current directory and specify it using this method of description Example for using include NC30 s command include can be nested in up to 8 levels If the specified file cannot be found in any directory searched NC30 outputs an include error includesx kcee e The standard include file is read from the standard directory include lt stdio h gt include usr global h The header of a global variable is read from the current directory main function ke void main void j Figure 1 9 1 Typical description of include 63 Introduction to C Language 1 9 Preprocess Commands 1 9 3 Macro Definition Use the define identifier for character string replacement and macro definition Normally use uppercase letters for this identifier to discriminate it from variables and functions This section explains how to define a macro and cancel a macro definition Defining a constant A constant can be assigned a name in the same way as in the assembler equ statement T
118. orage class specifiers that can be used here are static and extern This section explains how to specify the storage class of a function Global and local functions 1 If no storage class is specified for a function when defining it This function is assumed to be a global function that can be called and used from any other source file If a function is declared to be static when defining it This function is assumed to be a local function that cannot be called from any other source file If a function is declared to be extern in its type declaration This storage class specifier indicates that the declared function is not included in the source file where functions are declared and that the function in some other source file be called However only if a function has its type declared even though it may not be specified to be extern if the function is not found in the source file the function in some other source file is automatically called in the same way as when explicitly specified to be extern Source file 1 Source file 2 void funct void void func void extern void func2 void void func3 void UI void main void void func2 void Can be called Can be called static void func3 void j Figure 1 6 5 Storage classes of function 44 Introduction to C Language 1 6 Storage Classes Summary of storage classes Storage classes of variables are summarized in Table 1 6 1 Storage classes of
119. ory map setup files for MR30 The startup program provided by MR30 contains include files that determine memory map To modify memory map it is necessary to correct these included files Here the following explains the files related to memory map Table 3 3 1 Memory Map Related Files for MR30 An include file to allocate memory for program Used for development in C C Sec inc and data when using NC30 language An include file to allocate memory for program Used for development in A Jand data when using AS30 only assembly language 139 Using Real time OS MR30 3 3 Development Procedures Using MR30 3 3 2 Flow of Development Using MR30 This section explains the flow of development of a program with built in MR30 Flow of development using MR30 Figure 3 3 7 shows the flow of program development when using MR30 in the program Startup program C language SEODIQULA OR Me corrected source file System generation procedure System data description fie definition file Du AE s makefile T sourcefile source file it J Linkage editor In30 Load module converter Imc30 Machine language file P Writing into ROM Figure 3 3 7 Development flow Development procedures To develop a program follow the procedures below Design and create each task and handler Correct the startup program Correct memory map Create a configuration file Start up the configurator Creat
120. priority may occur when executing an OS dependent interrupt handler Figure 3 1 5 shows how OS dependent interrupt handlers operate when multiple interrupts occur lt Task 1 gt lt OS dependent interrupt handler 1 gt OS dependent interrupt handler 2 gt Priority low Priority high Registers saved System call issued l Registers saved System call issued Interrupt Interrupt Registers restored Registers restored Dispatch not performed Returns to the first interrupt handler Dispatch occurs Task switching in handlers 1 and 2 are performed here Figure 3 1 5 Execution of OS dependent interrupt handlers when multiple interrupts occur When multiple interrupt occur the system call ret int in the OS dependent interrupt handler that was invoked for an interrupt of high priority does not perform task dispatch This is because all processing of the OS dependent interrupt handler must be completed before returning to the task 129 Using Real time OS MR30 3 3 1 Basics of Real time OS 3 1 4 Special Handlers In addition to the interrupt handlers described above MR30 has some other handlers that utilize the functions of the real time OS This section explains about such special handlers System clock interrupt handler The system clock interrupt handler is a special handler provided by the real time OS This handler is used for time management by using one hardware timer as the system clock exclusively for
121. processor mode register to suit the tem 02H 000AH ze 400H PMOD Set Processor Mode Register 00H O00AH 0080h flg __ Sys _ Sp amp OFFFFH sp __ Sys Sp amp OFFFFH fb data_SE_top sb Figure 3 3 2 Initializing M16C 60 M16C 20 control registers Note Memory map cannot be modified in the startup program To do this correct MR30 s section definition file c sec inc 136 Using Real time OS MR30 3 3 3 Development Procedures Using MR30 Setting of interrupt vector table start address crtOmr a30 c sec inc Set the start address of the interrupt vector table The values set here are set to the interrupt table register INTB in crtOmr a30 crt mr a30 Set System Stack Pointer and oet Interrupt Vector 4 Sys Sp amp OFFFFH ISP set initial ISP mov b 0 ROL mov b _ SYS IPL ROH Idc RO FLG set system IPL Idc 4 INT VECTOR 516 amp 0FFFFH INTBH Idc 4 INT VECTOR amp OFFFFH INTBL enable interrupt c sec inc The values defined in c sec inc are set to the interrupt table register INTB glb HE section INFERRUPT VECTOR Interrupt vector table org __INT_VECTOR Figure 3 3 3 Setting interrupt vector table start address Initialization of peripheral I Os used crt mr a30 Add the initial setup procedure for peripheral I Os to the startup program by writing them in crtOmr a30 Figure 3 3 4 shows the location for these initial settings to be written Add init
122. program finds the sum of integers from 1 to 100 void sum void Declares sum function Refer to Section 1 5 Functions unsigned int total 0 Declares the variables used void sum void Defines sum function unsigned int i 0 Defines and initializes counter variables i total i jwhile i lt 100 Loops until the counter content increments from 1 to 100 j Example 1 4 6 Finding sum total 3 do while statement 34 Introduction to C Language 1 4 Control Statements 1 4 4 Suspending Processing There are control statements auxiliary control statements such as break continue and goto statements that make it possible to suspend processing and quit This section explains how to write these control statements and shows some examples of usage break statement Use this statement in repeat processing or in a switch case statement When break is executed the program suspends processing and exits only one block e When used in a while statement e When used in a for statement Is condition l expression Is expression 2 true true Execution statement Figure 1 4 8 Example for break statement continue statement Use this statement in repeat processing When continue is executed the program suspends processing After being suspended the program returns to condition determination when continue is used in a while statement or executes expression 3 before returning to condition determi
123. rea is used this method helps to save the amount of memory used Furthermore since explicit substitutions are checked when compiling the program it is possible to check rewrite errors const datatype variable name char a25 A 2 byte area const char c 10 is allocated Only 1 byte is allocated void main void Figure 2 1 6 const modifier and memory mapping ts ROM ing Technology 2 1 Memory Mapping 2 1 4 Controlling Memory Mapping of Struct When allocating memory for structs NC30 packs them in the order they are declared in order to minimize the amount of memory used However if the processing speed is more important than saving memory usage write a statement pragma STRUCT to control the method of mapping structs into memory This section explains NC30 s specific extended functions used for mapping structs into memory NC30 rules for mapping structs into memory NC30 follow the rules below as it maps struct members into memory 1 Structs are packed No padding occurs inside the struct 2 Members are mapped into memory in the order they are declared struct tag s11 int i char c Mapping int k MS s1 Figure 2 1 7 An image depicting how NC30 s default struct is mapped into memory Inhibiting struct members from being packed pragmaASTRUCTAtag nameAunpack This command statement inserts pads into a struct so that its total size of struct members equals even bytes Use this specification
124. riables Refer to 1 2 Date Types and 1 6 Storage Classes Type function name dummy argument Refer to 1 5 Functions Declaration of internal variables Refer to 1 2 Date Types and 1 6 Storage Classes Executable statement Refer to 1 3 Operators and 1 4 Control Statements Figure 1 1 3 Configuration of C language source file Introduction to C Language 1 1 Programming in C Language Programming style To increase the maintainability of a program it is necessary that a template for program list is determined by consultation between those who develop the program By sharing this template as a programming style among the developers it is made possible to write a source program that can be understood and maintained by anyone Figure 1 1 4 shows an example of a programming style Create a function separately for each functionality of the program Limit processing within one function unless specifically necessary A size not larger than 50 lines or so is recommended Do not write multiple executable statements in one line Indent each processing block successively normally 4 tab stops Clarify the program flow by writing comment statements as appropriate When creating a program from multiple source files place the common part of the program in an independent separate file and share it Enclose a comment statement with and x ooo Jf Test program s while processin Enclose
125. riting program when operating in single chip mode 89 ROM ing Technology 2 2 3 Extended Functions for ROM ing Purposes 2 3 Extended Functions for ROM ing Purposes 2 3 1 Efficient Addressing The maximum area accessible by the M16C 60 M16C 20 series is 1 Mbytes NC30 divides this area into a near area in addresses from 00000 to OFFFF and a far area in addresses from 00000 to FFFFF for management purposes This section explains how to arrange and access variables and functions in these areas The near and the far areas NC30 divides a maximum 1 Mbytes of accessible space into the near area and the far area for management purposes Table 2 3 1 lists the features of each area Table2 3 1 near Area and far Area Area name Feature This space is where the M16C 60 M16C 20 series can access data efficiently near area ltis a 64 Kbyte area in absolute addresses from 00000 to OFFFF in which stacks and internal RAM are located This is the entire 1 Mbyte memory space in absolute addresses from 00000 to far area FFFFF that can be accessed by the M16C 60 Internal ROM etc are located in this area Default near far attributes NC30 discriminates the variables and functions located in the near area as belonging to the near attribute from those located in the far area as belonging to the far attribute Table 2 3 2 lists the default attributes of variables and functions Table 2 3 2 Default near far Attributes Classification
126. rmally written Not discriminated and lowercase in lowercase Allocation of data Specified by data type Specified by a number of bytes area using pseudo instruction Input output instructions available However it depends on hardware and software Input output No input output instructions instruction available Note This refers to standard specifications stipulated for the C language by the American National Standards Institute ANSI to maintain the portability of C language programs Introduction to C Language 1 1 Programming in C Language 1 1 2 Program Development Procedure An operation to translate a source program written in the C language into a machine language program is referred to as compiling The software provided for performing this operation is called a compiler This section explains the procedure for developing a program by using NC30 the C compiler for the M16C 60 M16C 20 series of Mitsubishi single chip microcomputers NC30 product list Figure 1 1 1 lists the products included in NC30 the C compiler for the M16C 60 M16C 20 series of Mitsubishi single chip microcomputers Compile driver nc30 It starts up the compiler assembler or linker Preprocessor cpp30 It processes macro and conditional compiling Compiler main unit ccom30 It converts C language source files into assembly language source files NC30 product Stack size calculating utility package stk30 It calculates th
127. rogram will start Idintb VECTOR ADR Figure 2 2 8 Setting the start address of interrupt vector table Setting the processor operation mode ncrt0 a30 Set the processor operation mode In the same way add the instructions here that directly controls the operation of the M16C 60 M16C 20 such as one that sets the system clock Figure 2 2 9 shows locations where to add these instructions and how to write the instruction statements After a reset the program starts from this label terrupt section start glb start section interrupt Add settings matched to the system 30000001 1B 000AH disable register protect 31100001 1 1B 0004H processor mode register O 00001000B 0006H system clock control register O 00100000B 0007H system clock control register 1 00000000B 000AH enable register protect Idc 0080H flg Idc stack_top 1 sp Idc istack_top 1 isp Idc stack_top 1 fb Idc data_SE_top sb Idinto VECTOR_ADR Figure 2 2 9 Setting the processor operation mode 85 ROM ing Technology 2 2 Startup Program Arranging each section and setting start address sect30 inc Arrange the sections generated by NC30 and set their start addresses Use the pseudo instruction org to specify the start address of each section If any section does not have a specified start address memory for it is allocated in a contiguous location following the previously defined section Specify the start address of each area i
128. ructured programming i e sequential processing branch processing and repeat processing can all be written in a control statement For this reason it is possible to write a program whose flow of processing can easily be traced A program can easily be divided into modules A program written in the C language consists of basic units called functions Since functions have their parameters highly independent of others a program can easily be made into parts and can easily be reused Furthermore modules written in the assembly language can be incorporated into a C language program directly without modification An easily maintainable program can be written For reasons 1 and 2 above the program after being put into operation can easily be maintained Furthermore since the C language is based on standard specifications ANSI standard 9 a program written in the C language can be ported into other types of microcomputers after only a minor modification of the source program Comparison between C and assembly languages Table 1 1 1 outlines the differences between the C and assembly languages with respect to the method for writing a source program Table 1 1 1 Comparison between C and Assembly Languages C language Assembly language Basic unit of program Method of Function Function name Subroutine Subroutine name description Discrimination Uppercase and lowercase are between uppercase discriminated No
129. sed to define data type in system call EH err code Places its own task in WAIT state err code slp tsk l Determines error code after clearing WAIT if err_code E OK ext tsk Error codes of slp_tsk are E OK and E RLWAI Figure 3 2 4 Utilization of error code Note Usable error codes vary with each system call 133 Using Real time OS MR30 3 2 Method for Using System Calls Column Defined character strings MR30 has defined character strings regarding the data types of system call parameters and specific other data types These character strings are standardized to maintain compatibility between the real time OSs based on uITRON specifications Table 3 2 2 Data Types and Characters opecific data Signed 8 bit integer Signed 16 bit integer H Signed 32 bit integer Unsigned 8 bit integer UB Unsigned 16 bit integer UH Unsigned 32 bit integer Pointer to unmatching data types Parameter data CINRENEJCIORENNNEJLSTT CNN 134 Using Real time OS MR30 3 3 3 Development Procedures Using MR30 3 3 Development Procedures Using MR30 3 3 1 Files Required during Development When developing a program using MR30 there must be a startup program and an object definition file available in addition to the program itself This section explains the contents of each file MR30 startup program The need for a startup program was discussed in Section 2 2 Startup Program
130. sembly language program 1 Follow NC30 s symbol conversion rules for the labels of the called subroutine 2 Write the C language function in a file separately from the assembly language program 3 In the assembly language file declare external references using AS30 s pseudo instruction glb before calling the C language function Assembly language C language External reference of function s beginning label symbol glb Saving registers func argument Setting arguments Allocating area for storing return values JSR func JSR func Freeing area that contains return values Freeing argument area Restoring registers Figure 2 4 10 Calling C language function 111 ROM ing Technology 2 2 5 Interrupt Processing 2 5 Interrupt Processing 2 5 1 Writing Interrupt Processing Functions NC30 allows you to write interrupt processing as C language functions There are two procedures to be followed 1 Write interrupt processing functions 2 Register them in an interrupt vector table This section explains how to write C language functions for each type of interrupt processing Writing hardware interrupts pragma INTERRUPT pragma A INTERRUPT A interrupt function name When an interrupt function is declared as shown above NC30 generates instructions to save and restore all registers of the M16C 60 M16C 20 and the reit instruction at entry and exit of the specified function in addition to or
131. specified by include exists Up to 8 directories can be specified E Invokes only preprocess command and outputs result to standard output device D identifier directory name Invokes only preprocess command and creates file attribute i Creates assembly language source file attribute a30 Lucus Lus i processing U U predefined macro name macro name Undefines Undefines specified predefined macro predefined macro Inhibits copyright message from being output at startup If startup options c E P and S are not specified NC30 controls the compile driver up to In30 until it creates the absolute module file attribute x30 Appedix 6 l Appendix B Appendix B NC30 Command Reference Output file specifying options Table B 2 Output File Specifying Options MER opecifies the name of file generated by nc30 e g absolute module file map file Do not write file extension Version information display options Table B 3 Version Information Display Options Displays command program name and command line under execution V Displays message when compiler s each program starts up before terminating processing does not perform compile processing Debug options Table B 4 Debug Options Outputs debug information to assembly language source file attribute a30 Bum When calling function it always outputs enter instruction Be sure to specify this option when using debugger s stac
132. t void func2 int char Main function void main int a 40 b 29 int ans char c 0xFF Calls function 1 func1 using a as argument Return value is substituted for ans ans funci a func2 b c Calls function 2 func2 using b c as arguments There is no return value Definition function 1 int funci int x return Z Returns a value for the argument x Definition function 2 using a return statement void func2 int y char m Figure 1 5 2 Example for a function 39 Introduction to C Language 1 5 Functions 1 5 3 Exchanging Data between Functions In the C language exchanges of arguments and return values between functions are accomplished by copying the value of each variable as it is passed to the receiver Call by Value Consequently the name of the argument used when calling a function and the name of the argument dummy argument received by the called function do not need to coincide Since processing in the called function is performed using copied dummy arguments there is no possibility of damaging the argument proper in the calling function For these reasons functions in the C language are independent of each other making it possible to reuse the functions easily This section explains how data are exchanged between functions Example 1 5 1 Finding Sum of Integers example for a function In this example using two arbitrary integers in the rang
133. t gt expression 2 equal to the value of expression 2 and substitutes the 18 Introduction to C Language 1 3 Operators Column 3 Implicit type conversion When performing arithmetic or logic operation on different types of data NC30 converts the data types following the rules shown below This is called implicit type conversion Data types are adjusted to the data type whose bit length is greater than the other before performing operation e When substituting data types are adjusted to the data type located on the left side of the equation word byte byte word int char char lt int char byte 0x12 Ox When int word 0x3456 ox oo 12 0x00 is extended Upper 1 byte is cut Figure 1 3 1 Assign different types of data Introduction to C Language 1 3 Operators 1 3 3 Operators for Processing Data The operators frequently used to process data are bitwise operators and shift operators This section explains these bitwise and shift operators Bitwise operators Use of bitwise operators makes it possible to mask data and perform active conversion Table 1 3 5 Bitwise Operators Returns the logical product of the values of expression 1 amp expression 2 l l l expressions 1 and 2 after ANDing each bit Returns the logical sum of the values of expression 1 expression 2 l l expressions 1 and 2 after ORing each bit l Returns the exclusive logical sum of
134. t a time Figure C 1 Example for writing transfers of structs Appedix 12 l Appendix C Appendix C Questions amp Answers Reducing generated code 1 lt Question gt We wish to reduce the amount of generated code What points should we check Answer Check the following points When declaring data 1 Among the data declared to be the int type is there data that falls within the following range If any correct its data type Designations in can be omitted Unsigned int type that falls within 0 to 255 Correct it to the unsigned char type signed int type that falls within 128 to 127 Correct it to the signed char type 2 Among the data other than the int type where the unsigned signed modifiers are omitted is there data that does not have a negative value If any add the unsigned modifier In NC30 data other than the int type assumes the signed modifier by default When declaring bit data 1 Is there any bit data using a bit field for which pragma BIT is not declared Always be sure to declare pragma BIT For direct 1 bit instructions to be generated in NC30 it is necessary to declare ft pragma BIT as well as a bit field When compiling 1 Is the optimization option OR specified If not specify this option When the optimization option OR is specified in NC30 it optimizes code generation by placing emphasis on ROM efficiency Appedix 13 l App
135. t begins with the symbol to discriminate them from other execution statements Although they can be written at any position the semicolon to separate entries is unnecessary Table 1 9 1 lists the main preprocess commands that can be used in NC30 Table 1 9 1 Main Preprocess Commands of NC30 ifdef to elif to else to ae l Performs conditional compile endif ifndef to elif to else to Performs conditional compile endif Hero Outputs message to standard output devices before suspending processing Specifies a file s line numbers Outputs alarm when constant expression is false Instructs processing of NC30 s extended function This is pragma NAM detailed in Chapter 2 62 Introduction to C Language 1 9 Preprocess Commands 1 9 2 Taking in A File Use the command include to take in another file NC30 requires different methods of description depending on the directory to be searched This section explains how to write the command include for each purpose of use Searching for standard directory include file name gt This statement takes in a file from the directory specified with the startup option I If the specified file does not exist in this directory NC30 searches the standard directory that is set with NC30 s environment variable INC30 as it takes in the file As the standard directory normally specify a directory that contains the standard include file Searching f
136. t_int To terminate an OS dependent interrupt handler MR30 uses a special system call named ret int Scheduling and dispatching are performed in this system call oince a dispatch is performed when an OS dependent interrupt handler is terminated the task that is in the RUN state at termination of the handler is not necessarily the one that was in the RUN state when an interrupt occurred 127 Using Real time OS MR30 3 3 1 Basics of Real time OS Executing OS dependent interrupt handler Figure 3 1 4 shows how an OS dependent interrupt handler is executed in comparison with invocation by a system call Invocation by system call gt lt Invocation from handler gt C Cate C Registers saved and stacks switched Registers saved issued and task wait cleared Execution tasks Registers restored Handler Stacks switched terminating Execution tasks and registers system call switched and dispatch restored System call issued System call i System call Note processed RTM Acronym of Real time Monitor Figure 3 1 4 Executing OS dependent interrupt handler during task execution Note The system calls that can be used in interrupt handlers are limited Be sure to use the system calls that are usable in interrupt handlers 128 Using Real time OS MR30 3 1 Basics of Real time OS Management of multiple interrupts Multiple interrupts could occur e g an interrupt of higher interrupt enable
137. tacks used is 25 byes Figure 2 2 3 Method for calculating the maximum size of stacks used 81 ROM ing Technology 2 2 Startup Program Automatically calculating the maximum size of stacks used If the program structure is simple it is possible to estimate the stack sizes used by following the method described above However if the program structure is complicated or when the program uses internal functions calculations require time and labor In such a case Mitsubishi recommends using the stack size calculating utility stk30 that is included with NC30 It automatically calculates the maximum size of stacks used from the stack size usage information file xxx stk that is made at compiling and outputs the result to standard output devices Furthermore if a startup option o is added it outputs the relationship of function calls along with the calculation result to a calculation result display file xxx siz To estimate an interrupt stack size it is necessary to calculate the stack sizes used by each interrupt function and those used by the functions called by the interrupt function In this case use a startup option e function name If this startup option is used along with o the stk30 utility outputs the stack sizes used below a specified function and the relationship of function calls Figure 2 2 4 shows the processing results of stk30 by using the sample program described above Standard output Stack size usage s
138. ted However there are some data that are changed by an interrupt or input from a port irrespective of program processing Write the type qualifier volatile when declaring such data NC30 does not optimize the data that is accompanied by this type qualifier and outputs instruction code for it void main void char porti volatile char port2 Optimized and no code is output port because it is only read porte Code is output without optimizing Figure 1 2 6 Example for writing the type qualifier volatile Column 7 Syntax of declaration When declaring data write data characteristics using various specifiers or qualifiers along with the data type Figure 1 2 7 shows the syntax of a declaration Declaration specifier otorage class Declarator specifier Type Type data name static unsigned int dataname register signed char auto const float extern volatile struct union Figure 1 2 7 Syntax of declaration 1 3 Operators 1 3 1 Operators of NC30 Introduction to C Language 1 3 Operators NC30 has various operators available for writing a program This section describes how to use these operators for each specific purpose of use not including address and pointer operators Note and the precautions to be noted when using them Operators usable in NC30 Table 1 3 1 lists the operators that can be used in NC30 Table 1 3 1 Operators Usable
139. ters The following lists the main specification items 1 Standardization of system call names 2 Definition of task status RUN WAIT and READY are essential Note The uITRON specifications are copyrighted by Dr K Sakamura of the University of Tokyo 123 Using Real time OS MR30 3 1 Basics of Real time OS 3 1 2 Functions of Real time OS The three primary functions of the real time OS are task scheduling task dispatch and object management This section explains about these functions Task scheduling Several tasks and not just one in a system can be in the READY state However it is always only one task that is in the RUN state Therefore the real time OS must choose one task from those in the READY state that is placed in the RUN state next This selection process is called scheduling Among several methods of scheduling MR30 uses a priority method Priority method Each task is assigned priority or weight and the task with higher priority than other tasks is placed in the RUN state first If two or more tasks with the same priority exist the task that is placed in the READY state first is given priority Task priorities are set by the user as necessary and not set by the real time OS Priority resolution among tasks is the most important point in using the real time OS Context and task control block TCB The process of placing a task in the READY state into a RUN state by the real time OS is re
140. that are found in the 7700 family are nonexistent Furthermore although the interrupt programs in the 7700 family were subjected to restrictions on allocatable addresses they in the M16C 60 M16C 20 series can be mapped into any desired location over the entire memory space just like ordinary other programs Therefore NC77 s interrupt section is nonexistent in NC30 and the interrupt programs in NC30 are stored and located in the program section Moreover the M16C 60 M16C 20 series has two types of interrupt vector tables a variable vector table that can be located at any desired address in the entire memory space and a fixed vector table which has its location address predetermined for each type of microcomputer In NC30 the former is located as the vector section and latter as the fvector section Table A 1 lists the differences between NC30 and NC77 regarding sections Table A 1 Functional Comparison Regarding Sections NC30 NC77 ack An area used as stack It is located at An area used as stack It is located in addresses from 00400H to OFFFFH bank 0 of the 7700 family Stores the contents of the M16C 60 s M16C 20 s interrupt vector table The interruot vector table can be located at i vector P which this interrupt vector table is Stores the contents of the 7700 family s interrupt vector table The address at any desired address in the M16C 60 s entire memory space by INTB register relative Stores the contents of
141. the M16C 60 M16C 20 series Table A 4 Extended Functions Not Supported by NC30 oragma LOADDT When calling a meteor it returns data bank register DT to the value when compiled piesa Set the m flag to 1 before calling a function M1FUNCTION The extended functions listed in Table A 5 are supported by NC30 also for reasons of compatibility with NC77 However when creating a new program please follow the recommended uses below without using these extended functions Table A 5 Extended Functions Retained for Compatibility Reason and Recommended Uses in NC30 fies i l pragma INTF pen Rue process Use pragma INTERRUPT function ifi f pragma EQU D Use pragma ADDRESS variable Appedix 5 l Appendix B Appendix B NC30 Command Reference Appendix B NC30 Command Reference NC30 command input format nc30 A startup option A assembly language source file name A relocatable object file name A C language source file name gt 2e Indicates the prompt lt gt Indicates an essential item Indicates items that can be written as necessary Indicates a space When writing multiple options separate them with the space key Options regarding compile driver control Table B 1 Options Regarding Compile Driver Control Creates relocatable file attribute r30 before terminating processing Defines identifier It functions in the same way as define opecifies directory name where file
142. the startup program RAM area ROM area char moji 2 A Initial value of moji int seisu 0x1234 void main void L L7 Block transfer from ROM to RAM Initial value of seisu j otartup program RAM area Setting of initial values completed Figure 2 1 2 Handling of static variables with initial values 1 ROM ing Technology 2 1 Memory Mapping 2 1 2 Sections Managed by NC30 NC30 manages areas in which data and code are located as sections This section explains the types of sections generated and managed by NC30 and how they are managed Sections types NC30 classifies data into sections by type for management purposes See Figure 2 1 3 Table 2 1 1 lists the sections types managed by NC30 Table 2 1 1 Sections types Managed by NC30 Section base name Content Contains static variables with initial values Contains static variables without initial values Contains character strings and constants Contains programs Variable vector area compiler does not generate Fixed vector area compiler does not generate Stack area compiler does not generate Heap area compiler does not generate pi data section EM bss section Static int 1 2 1 variables with initial values char c 0 Static variables without initial const char cc a variables void main void T T RAM rograms program section Character strings mE l rom section ROM
143. the startup program The following explains the startup programs supplied with NC30 ncrt0 a30 and sect30 inc Roles of startup program The following lists the roles performed by the startup program 1 Allocate a stack area 2 Initialize the microprocessor Initialize a static variable area Call the main function Set the interrupt vector table 3 4 Set the interrupt table register INTB 5 6 78 ROM ing Technology 2 2 Startup Program Structure of sample startup programs NC30 s startup program consists of two files ncrt0 a30 and sect30 inc ncrt0 a30 sect30 inc Set size of heap area Set arrangement of each section Set size of stack area Set start address of interrupt Set start address of section vector table Set variable vector table include sect30 inc Set SB area Define macro for initializing variable area Program part Set processor operation mode Initialize stack pointer Initialize FB and SB registers Initialize INTB register Set fixed vector table Initialize near area of data Initialize far area of data Initialize heap area Initialize standard I O function library Call main function Figure 2 2 1 Structure of sample startup program 9 ROM ing Technology 2 2 Startup Program 2 2 2 Estimating Stack Sizes Used Set an appropriate stack size in the startup program If the stack size is excessively small the system could run out of control
144. ther and boy As the family grows so do the type declaration of variables and the execution statements to be initialized void main void int father 29 int mother 24 void main void int boy 4 int total int father 29 int mother 24 int boy 4 int sister 1 1 int sister 2 1 total father mother boy int total total father mother boy sister 1 sister 2 Example 1 7 1 Finding total age of a family 1 46 Introduction to C Language 1 7 Arrays and Pointers 1 7 2 Creating an Array There are two types of arrays handled in the C language one dimensional array and two dimensional array This section describes how to create and reference each type of array One dimensional array A one dimensional array has a one dimensional linear expanse The following shows the declaration format of a one dimensional array Data type array name number of elements When the above declaration is made an area is allocated in memory for the number of elements with the array name used as the beginning label To reference a one dimensional array add element numbers to the array name as subscript However since element numbers begin with 0 the last element number is 1 less than the number of elements Declaration of one dimensional array Declaration and initialization of one dimensional array 8 bits Nm buff 1 buff1 0 char buff1 3 buff1 1
145. this purpose Table 3 1 5 Interrupt Handler Provided by Real time OS This handler is provided by the real time monitor for timer interrupts Any timer can be chosen for this purpose This timer is required when using a time management function of the OS One timer is occupied for this purpose The timer also can be disabled from use System clock interrupt handler The cycle time of the system clock interrupt handler i e timer interrupt generation intervals can be set as desired by the user Special handlers All handlers listed in Table 3 1 6 are invoked as part of the system clock interrupt handler For this reason system calls can be used in these handlers Table 3 1 6 Special Handlers Invoked from inside the system clock interrupt handler periodically at time intervals set Since Cyclic handler this handler functions as part of the system Prepared by the user clock interrupt handler it assumes the form of a subroutine Invoked from inside the system clock interrupt handler only once in a set duration of time Alarm handler Since this handler functions as part of the Prepared by the user system clock interrupt handler it assumes the form of a subroutine 130 Using Real time OS MR30 3 3 2 Method for Using System Calls 3 2 Method for Using System Calls 3 2 1 MR30 s System Calls This section explains about the system calls that are required when using the real time OS by describing in which form MR3
146. tk30 sample stk gt stk30 sample stk information A AR f A file sample stk xxx Stack Size xx Stk30 o sample stk 25 bytes Iculat It display fil le si 9 amp stk30 o efunc sample stk Calculation result display file sample siz Stack size used from func1 xxx Stack Size 25 bytes 12 bytes xxx C Flow sx xxx C Flow main sample stk func1 sample stk func3 sample stk func2 sample stk func1 sample01 stk func3 sample01 stk Figure 2 2 4 Stack size calculating utility stk30 82 ROM ing Technology 2 2 2 Startup Program 2 2 3 Creating Startup Program The sample startup program shown above must be modified to suit the C language program to be created This section describes details on how to modify the sample startup program Modifying sample startup program Modify the following points to suit the C language program to be created ncrt0 a30 Setting size of heap area Setting size of stack area Setting start address of interrupt vector table Setting processor mode register Arranging sections and setting start address Setting variable vector table Setting fixed vector table Figure 2 2 5 Points to be modified in sample startup program 83 ROM ing Technology 2 2 Startup Program Setting the size of heap area ncrt0 a30 oet the required memory size to be allocated when using memory management functions calloc malloc Set 0 when not using
147. tructing a stack frame Figure 2 4 3 shows how a stack frame is constructed by tracing the flow of a C language program 1 main under void main void execution Stack frame of main function int i char c func i c 2 Immediately before Stack frame of jumping to main function func void func int x char y Automatic variable of func io ane y i Old frame pointer Processing of func ao O naa E completed Argument i x Argument c y Stack frame of main function Figure 2 4 3 Constructing a stack frame 101 ROM ing Technology 2 4 Linkage with Assembly Language Rules for passing arguments NC30 has two methods for passing arguments to a function via a register and via a stack When the following three conditions are met arguments are passed via a register otherwise arguments are passed via a stack 1 The types of the function s arguments are prototype declared 2 One or more arguments are the type that can be assigned to a register 3 No short cut form is used in the argument part of prototype declaration Table 2 4 1 Rules for Passing Arguments Third and following Type of argument First argument Second argument arguments short int types H1 R2 Stack near pointer type Other types Stack Stack Stack Prototype declaration 2 kx void func1 char char char void func2 int int void main void Register R1 char a b c Argumenta int
148. uble quotations can be handled as a character string constant Character string constants have the null character O automatically added at the end of data to denote the end of the character string Example abc 012 n Hello Memory 2 bytes of data area Character 3 bytes of A set of single are used strin data area character 9 resid constants constant Figure 1 2 2 Difference between a b and ab Column List of control codes escape sequence The following shows control codes escape sequence that are frequently used in the C language Table 1 2 2 Escape Sequence in C Language Form feed FF Single quotation New line NL Double quotation constant Horizontal tab HT Octal value x constant value Introduction to C Language 1 2 Data Types 1 2 2 Variables Before a variable can be used in a C language program its data type must first be declared in the program The data type of a variable is determined based on the memory size allocated for the variable and the range of values handled This section explains the data types of variables that can be handled by NC30 and how to declare the data types Basic data types of NC30 Table 1 2 3 lists the data types that can be handled in NC30 Descriptions enclosed with in the table below can be omitted when declaring the data type Table 1 2 3 Basic Data Types of NC30 Range of values that
149. ure 3 4 7 Example for writing OS dependent interrupt handlers include lt mr30 h gt include id h static void int_hand void No static type functions can be defined as OS dependent interrupt handler Figure 3 4 8 Precautions for writing OS dependent interrupt handlers regarding static type functions 148 Using Real time OS MR30 3 4 Building MR30 into Program Using NC30 Data exchange between OS dependent interrupt handler and task There are two methods for exchanging data between an OS dependent interrupt handler and a task one by using an external variable and one by using a mail box Figure 3 4 9 shows an example of how data is exchanged using an external variable include lt mr30 h gt include id h char datai Declares external variable when exchanging data mE l with a task void int_hand void data1 0x10 iwup tsk ID task1 j void task1 void Uses the data from the OS dependent interrupt handler for slp tsk if data1 Figure 3 4 9 Example for data exchange by using an external variable Column 7 7 7 7 7 7 System calls usable in handlers Only specific system calls can be used in OS dependent interrupt handlers cyclic handlers and alarm handlers Note that if an unusable system call is used the program may not operate properly Note also that system calls in ixxx xxx form are provided for exclusive
150. value of num In cases where multiple branches are involved like in this example use of table jump makes it possible to call any desired subroutine in the same processing time However no registers can be specified for argument transfers by oragma PARAMETER Determination of num num gt 3 Addition language source subroutine file Subtraction subroutine Multiplication subroutine Division subroutine lt C language source file gt lt Assembly language source file gt section orogram mov w R1 RO add w R2 RO rts Prototype declaration int cal f int int int extern int jmptbl int int Externally references relevant table name as l function pointer int x 10 y Z int num val void main void R1 RO R2 RO J num 2 if num lt 4 val cal_f num x y cal f m x y mov w mov w int z int p int int exts w l Gets jump address di p jmptbl m iV W z p X y moVv w return z rts section rom FE ROMDATA glb jmptbl Uses function pointer to call subroutine Wad adai Externally declares i E table name word sub f Use pseudo instruction lword to register each subroutine s start address word mul f lword div f END Example 2 4 2 Calling a subroutine by table jump 109 ROM ing Technology 2 4 Linkage with Assembly Language Example 2 4 3 A Little Different Way to Use Table Jump Onc
151. with Assembly Language 2 5 Interrupt Processing This chapter describes precautions to be followed when creating built in programs by focusing on the extended functions of NC30 ROM ing Technology 2 2 1 Memory Mapping 2 1 Memory Mapping 2 1 1 Types of Code and Data There are various types of data and code that constitute a program Some are rewritable and some are not Some have initial values and some do not All data and code must be mapped into the ROM RAM and stack areas according to their properties This section explains the types of data and code that are generated by NC30 Data and code generated by NC30 Figure 2 1 1 shows the types of data and code generated by NC30 and their mapped memory areas Automatic To stack area Variable data variable With initial value To RAM and ROM areas Static wae Without initial value To RAM area Constant To ROM area Ead dsis character string To ROM area Program Figure 2 1 1 Types of data and code generated by NC30 and their mapped areas Handling of static variables with initial values Since static variables with initial values are rewritable data they must reside in RAM However if variables are stored in RAM initial values cannot be set for them To solve this problem NC30 allocates an area in RAM for such static variables with initial values and stores initial values in ROM Then it copies the initial values from ROM into RAM in
152. y each individual function after considering the relationship of function calls and handling of interrupts Figure 2 2 3 shows by using a sample program an example of how to calculate the maximum size of stacks used Source file sample c gt void main void int funci int int int func2 char char int func3 int void main void int m n long kekka1 kekka2 kekka1 func1 m n kekka2 func2 m n int func1 int x int y int z1 Z2 Z1 X yY z2 func3 z1 return Z2 j int func2 char x char y Z Z xX y return Z int func3 int x return x main 54 8213 bytes yee 2 func 542 7 bytes func2 func3 5 bytes 1 bytes 542 7 bytes nc30 fshow stack usage sample c Stack size usage information file sample stk gt FUNCTION main Stack size used CONEX by each function auto faregSize 0 bytes PUSH amp CALL func1 PUSH amp CALL func2 Stack size used when calling a function FUNCTION func1 context 5 bytes auto 2 bytes faregSize 0 bytes 0 bytes PUSH amp 0 bytes PUSH MAX CALL func3 FUNCTION func2 context 5 bytes auto 2 bytes faregSize 0 bytes 0 bytes PUSH MAX FUNCTION func3 context 5 bytes auto 0 bytes faregSize 0 bytes 0 bytes PUSH MAX 1 Stack size for path 134745225 bytes 2 Stack size for path 1341 47 21 bytes Maximum size of s

Download Pdf Manuals

image

Related Search

Related Contents

  DryPlates® ETC - Laboratorios MICROKIT  Dokumentation zur OpenBCM-Mailbox v1.05  USER MANUAL NOR  GAME ONE - Sem38.qxd  Manual ECONOMAX Chuveiros - Economax  Lyngdorf Audio SDA 2175 User's Manual  dossier - DSB Communication sa  

Copyright © All rights reserved.
Failed to retrieve file