首页资源分类嵌入式处理器其它 > An introduction to programming The Microchip PIC in CCS C

An introduction to programming The Microchip PIC in CCS C

已有 445122个资源

下载专区

上传者其他资源

文档信息举报收藏

标    签:PICMicrochipCprogramming

分    享:

文档简介

An introduction to programming

The Microchip PIC in CCS C

文档预览

PICmicro MCU C® An introduction to programming The Microchip PIC in CCS C By Nigel Gardner The information contained in this publication regarding device application and the like is intended by way of suggestion only and may be superseded by updates. No representation or warranty is given and no liability is assumed by Bluebird Electronics, Microchip Technology Inc., or CCS Inc., with respect to the accuracy or use of such information, or infringement of patents arising from such use or their compliance to EMC standards or otherwise. Use of Bluebird Electronics, Microchip Technology Inc. or CCS Inc. products as critical components in life support systems is not authorized except with express written approval by above mentioned companies. No licenses are conveyed, implicitly or otherwise, under intellectual property rights. Copyright ® Bluebird Electronics 2002. All rights reserved. Except as permitted under the copyright Act of 1976 US Code 102 101-122, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of Bluebird Electronics, with the exception of the program listings which may be entered, stored, and executed in a computer system, but may not be reproduced for publication. PIC® and PICmicro, is registered trademark of Microchip Technologies Inc. in the USA and other countries. Printed and bound in the USA. Cover Art by Loni Zarling. Circuit diagrams produced with Labcentre Isis Illustrator. Flowcharts produced with Corel Flow. 2 Preface Thanks go to Rodger Richey of Microchip Technology Inc. for the use of this notes on C for the PICmicro®MCU, Mark at CCS, Inc. and Val Bellamy for proofreading this book. This book is dedicated to my wise June and daughter Emma. 3 Contents Introduction History Why use C? PC based versus PICmicro®MCU Based Program Development Product Development Terminology Trying and Testing Code C Coding Standards Basics 1 C Fundamentals Structure of C Programs Components of a C Program #pragma main() #include printf Function Variables Constants Comments Functions C Keywords 2 Variables Data Types Variable Declaration Variable Assignment Enumeration typedef Type Conversions 3 Functions Functions Function Prototypes Using Function Arguments Using Function to Return Values Classic and Modern Function Declarations 4 Operators Arithmetic Relational Logical Bitwise 4 Increment and Decrement Precedence of 5 Program Control Statements If If-else ? for Loop while Loop do-while Loop Nesting Program Control Statements Break Continue Null Return 6 Arrays / Strings One Dimensional Arrays Strings Multidimensional Arrays Initializing Arrays Arrays of Strings 7 Pointers Pointer Basics Pointers and Arrays Passing Pointer to Functions 8 Structures / Unions Structure Basics Pointers to Structures Nested Structures Union Basics Pointers to Unions 9 PICmicro®MCU Specific C Inputs and Outputs Mixing C and Assembler Advanced BIT Manipulation Timers A/D Conversion Data Communications I2C Communications SPI Communications PWM LCD Driving 5 Interrupts Include Libraries Additional Information 6 Introduction Why use C? The C language was development at Bell Labs in the early 1970’s by Dennis Ritchie and Brian Kernighan. One of the first platforms for implementation was the PDP-11 running under a UNIX environment. Since its introduction, it has evolved and been standardized throughout the computing industry as an established development language. The PC has become a cost effective development platform using C++ or other favored versions of the ANSI standard. C is a portable language intended to have minimal modification when transferring programs from one computer to another. This is fine when working with PC’s and mainframes, but Microcontrollers and Microprocessors are different breed. The main program flow will basically remain unchanged, while the various setup and port/peripheral control will be micro specific. An example of this is the port direction registers on a PICmicro®MCU are set 1=Input 0=Output, whereas the H8 is 0=Input and 1=Output. The use of C in Microcontroller applications has been brought about by manufacturers providing larger program and RAM memory areas in addition to faster operating speeds. An example quoted to me – as a non believer – was: to create a stopclock function would take 2/3 days in C or 2 weeks in assembler. ‘Ah’ I hear you say as you rush to buy a C compiler – why do we bother to write in assembler? It comes down to code efficiency – a program written in assembler is typically 80% the size of a C version. Fine on the larger program memory sized devices but not so efficient on smaller devices. You pay the money and take you PIC!! 7 PC Based vs. PICmicro®MCU Based Program Development Engineers starting development on PC based products have the luxury of basic hardware pre-wired (i.e., keyboard, processor, memory, I/O, printer and visual display (screen)). The product development then comes down to writing the software and debugging the errors. Those embarking on a PIC based design have to create all the interfaces to the outside world in the form of input and output hardware. A PC programmer could write the message “Hello World” and after compiling, have the message displayed on the screen. The PIC programmer would have to build an RS232 interface, set up the comm. port within the PIC, and attach the development board to a comm. Port on a PC to enable the message to be viewed. ‘Why bother’ I hear you say (and so did I). It comes down to portability of the end product. If we could get the whole of a PC in a 40 pin DIL package (including monitor and keyboard) we would use it; today’s miniaturization does not reach these limits. We will continue to use Microcontrollers like the PIC for low cost and portable applications. The development tools for PIC based designs offer the developer basically the same facilities as the PC based development with the exception of the graphics libraries. Product Development Product development is a combination of luck and experience. Some of the simplest tasks can take a long time to develop and to perfect in proportion to the overall product – so be warned where tight timescales are involved. To design a product one needs: time – peace and quiet – a logical mind and most important of all a full understanding of the requirements. I find the easiest way to begin any development is to start with a clean sheet of paper together with the specification or idea. Start by drawing out a number of possible solutions and examine each to try to find the simplest and most reliable option. Do not discard the other ideas at this stage as there are possibly some good thoughts there. Draw out a flow chart, block diagram, I/O connection plan or any suitable drawing to get started. Build up a prototype board or hardware mimic board with all the I/O 8 configured. Don’t forget I/O pins can be swapped to make board layout easier at a later date – usually wit minimal modification to the software. Then start writing code – in testable blocks – and gradually build up your program. This saves trying to debug 2000 lines of code in one go! If this is your first project – THEN KEEP IT SIMPLE – try switching an LED or two on and off from push buttons to get familiar with the instructions, assembly technique and debugging before attempting a mammoth project. Build up the program in simple stages – testing as you go. Rework your flowchart to keep it up to date. The Idea An idea is born – maybe by yourself in true EUREKA style or by someone else having a need for a project – the basic concept is the same. Before the design process starts, the basic terminology needs to be understood – like learning a new language. So in the case of Microcontroller designs based on the PICmicro®MCU, the PIC language (instruction set, terms and development kit) needs to be thoroughly understood before the design can commence. Now let’s get started with the general terms, some facts about the PIC and the difference between Microprocessor and Microcontroller based systems. Terminology Let’s start with some basic terminology used. Microcontroller A lump of plastic, metal and purified sand, which without any software, does nothing. When software controls a microcontroller, it has almost unlimited applications. I/O A connection pin to the outside world which can be configured as input or output. I/O is needed in most cases to allow the microcontroller to communicate, control or read information. Software The information that the Microcontroller needs to operate or run. This needs to be free of bugs and errors for a successful application or product. Software can be written in a variety of languages such as C, Pascal or Assembler (one level up from writing your software in binary). Hardware The Microcontroller, memory, interface components, power supplies, signal conditioning circuits and all the components – connected to it 9 to make it work and interface to the outside world. Another way of looking at (especially when it does not work) is that you can kick hardware. Simulator The MPLAB® development environment has its own built-in simulator which allows access to some of the internal operation of the microcontroller. This is a good way of testing your designs if you know when events occur. If an event occurs ‘somewhere about there’, you might find the simulator restrictive. Full trace, step and debug facilities are, however, available. Another product for 16C5x development is the SIM ICE – a hardware simulator offering some of the ICE features but at a fraction of the cost. In Circuit Emulator (ICEPIC or PICmicro®MCU MASTER) a very useful piece of equipment connected between your PC and the socket where the Microcontroller will reside. It enables the software to be run on the PC but look like a Microcontroller at the circuit board end. The ICE allows you to step through a program, watch what happens within the micro and how it communicates with the outside world. Programmer A unit to enable the program to be loaded into the microcontroller’s memory which allows it to run without the aid of an ICE. They come in all shapes and sizes and costs vary. Both the PICSTART PLUS and PROMATE II from Microchip connect to the serial port. Source File A program written in a language the assembler and you understand. The source file has to be processed before the Microcontroller will understand it. Assembler / Compiler A software package which converts the Source file into an Object file. Error checking is built in, a heavily used feature in debugging a program as errors are flagged up during the assembly process. MPASM is the latest assembler from Microchip handling all the PIC family. Object File This is s file produced by the Assembler / Compiler and is in a form which the programmer, simulator or ICE understands to enable it to perform its function. File extension is .OBJ or .HEX depending on the assembler directive. List File This is a file created by the Assembler / Compiler and contains all the instructions from the Source file together with their hexadecimal values alongside and comments you have written. This is the most useful file to examine when trying to debug the program as you have a greater chance of following what is happening within the software than the Source file listing. The file extension is .LST Other Files The error file (.ERR) contains a list of errors but does not give any indication as to their origin. The .COD file is used by the emulator. 10 Bugs Errors created free of charge by you. These range from simpel typin errus to incorrect use of the software language syntax errors. Most of these bugs will be found by the compiler and shown up in a .LST file, others will have to be sought and corrected by trial and error. Microprocessor A microprocessor or digital computer is made up of three basic sections: CPU, I/O and Memory – with the addition of some support circuitry. Each section can vary in complexity from the basic to all bells and whistles. I/O DIGITAL PWM ANALOG RS232 I2C DATA ADDRESS CPU 4, 8, 16 BIT ADDRESS MEMORY RAM EPROM EEPROM WATCHDOG TIMER OSCILLATOR TYPICAL MICROPROCESSOR SYSTEM Taking each one in turn: Input/output (I/O) can comprise digital, analog and special functions and is the section which communicates with the outside world. The central processor unit (CPU) is the heart of the system and can work in 4, 8, or 16 bit data formats to perform the calculations and data manipulation. The memory can be RAM, ROM, EPROM, EEPROM or any combination of these and is used to store the program and data. An oscillator is required to drive the microprocessor. Its function is to clock data and instructions into the CPU, compute the results and then output the information. The oscillator can be made from discrete components or be a ready made module. 11 Other circuitry found associated with the microprocessor are the watch dog timer – to help prevent system latch up, buffering for address and data busses to allow a number of chips to be connected together without deteriorating the logic levels and decode logic for address and I/O to select one of a number of circuits connected on the same bus. It is normal to refer to a Microprocessor as a product which is mainly the CPU area of the system. The I/O and memory would be formed from separate chips and require a Data Bus, Address Bus and Address Decoding to enable correct operation. Microcontrollers The PICmicro®MCU, on the other hand, is a Microcontroller and has all the CPU, memory, oscillator, watchdog and I/O incorporated within the same chip. This saves space, design time and external peripheral timing and compatibility problems, but in some circumstances can limit the design to a set memory size and I/O capabilities. The PIC family of microcontrollers offers a wide range of I/O, memory and special functions to meet most requirements of the development engineer. You will find many general books on library shelves exploring the design of microcontrollers, microprocessors and computers, so the subject will not be expanded or duplicated here other than to explain the basic differences. Why use the PIC Code Efficiency The PIC is an 8 bit Microcontroller based on the Harvard architecture – which means there are separate internal busses for memory and data. The throughput rate is therefore increased due to simultaneous access to both data and program memory. Conventional microcontrollers tend to have one internal bus handling both data and program. This slows operation down by at least a factor of 2 when compared to the PICmicro®MCU. Safety All the instructions fit into a 12 or 14 bit program memory word. There is no likelihood of the software jumping onto the DATA section of a program and trying to execute DATA as instructions. This can occur in a non Harvard architecture microcontroller using 8-bit busses. Instruction Set There are 33 instructions you have to learn in order to write software for the 16C5x family and 14 bits wide for the 16Cxx family. Each instruction, with the exception of CALL, GOTO or bit testing instructions (BTFSS, INCFSZ), executes in one cycle. Speed The PIC has an internal divide by 4 connected between the oscillator 12 and the internal clock bus. This makes instruction time easy to calculate, especially if you use a 4 MHz crystal. Each instruction cycle then works out at 1 uS. The PIC is a very fast micro to work with e.g. a 20MHz crystal steps through a program at 5 million instructions per second! – almost twice the speed of a 386SX 33! Static Operation The PIC is a fully static microprocessor; in other words, if you stop the clock, all the register contends are maintained. In practice you would not actually do this, you would place the PIC into a Sleep mode – this stops the clock and sets up various flags within the PIC to allow you to know what state it was in before the Sleep. In Sleep, the PIC takes only its standby current which can be less the 1uA. Drive Capability The PIC has a high output drive capability and can directly drive LEDs and triacs etc. Any I/O pin can sink 25mA or 100mA for the whole device. Options A range of speed, temperature, package, I/O lines, timer functions, serial comms, A/D and memory sizes is available from the PIC family to suit virtually all your requirements. Versatility The PIC is a versatile micro and in volume is a low cost solution to replace even a few logic gates; especially where space is at a premium. 13 PIC FUNCTION BLOCK DIAGRAM PIC16F84A(14Bit) BLOCK DIAGRAM 14 Security The PICmicro®MCU has a code protection facility which is one of the best in the industry. Once the protection bit has been programmed, the contents of the program memory cannot be read out in a way that the program code can be reconstructed. Development The PIC is available in windowed form for development and OTP (one time programmable) for production. The tools for development are readily available and are very affordable even for the home enthusiast. Trying and Testing Code Getting to grips with C can be a daunting task and the initial outlay for a C compiler, In Circuit Emulator and necessary hardware for the PIC can be prohibitive at the evaluation stage of a project. The C compiler supplied on this disk was obtained from the Internet and is included as a test bed for code learning. Basic code examples and functions can be tried, tested and viewed before delving into PIC specific C compilers which handle I/O etc. C Coding Standards Program writing is like building a house – if the foundations are firm, the rest of the code will stack up. If the foundations are weak, the code will fall over at some point or other. The following recommendations were taken from a C++ Standards document and have been adapted for the PIC. Names – make them fit their function Names are the heart of programming so make a name appropriate to its function and what it’s used for in the program. Use mixed case names to improve the readability ErrorCheck is easier than ERRORCHECK Prefix names with a lowercase letter of their type, again to improve readability: g Global gLog; r Reference rStatus(); s Static sValueIn; Braces{} Braces or curly brackets can be used in the traditional UNIX way if (condition) { ……………. } or the preferred method which is easier to read if (condition) 15 { ……………. } Tabs and Indentation Use spaces in place of tabs as the normal tab setting of 8 soon uses up the page width. Indent text only as needed to make the software readable. Also, tabs set in one editor may not be the same settings in another – make the code portable. Line Length Keep line lengths to 78 characters for compatibility between monitors and printers. Else If Formatting Include an extra Else statement to catch any conditions not covered by the preceding if’s if (condition) { } else if (condition) { } else { ……….. /* catches anything else not covered above */ } Condition Format Where the compiler allows it, always put the constant on the left hand side of an equality / inequality comparison, If one = is omitted, the compiler will find the error for you. The value is also placed in a prominent place. if ( 6 == ErrorNum) … Initialize All Variables Set all variables to a known values to prevent ‘floating or random conditions’ int a=6, b=0; Comments Comments create the other half of the story you are writing. You know how your program operates today but in two weeks or two years will you remember, or could someone else follow your program as it stands today? Use comments to mark areas where further work needs to be done, errors to be debugged or future enhancements to the product. 16 Basics All computer programs have a start. The start point in Microcontrollers is the reset vector. The 14 bit core (PIC16Cxx family) reset at 00h, the 12 bit core (PIC16C5x and 12C50x) reset at the highest point in memory – 1FFh, 3FFh, 7FFh. The finish point would be where the program stops if run only once e.g. a routine to set up a baud rate for communications. Other programs will loop back towards the start point such as traffic light control. One of the most widely used first programming examples in high level languages like Basic or C is printing ‘Hello World’ on the computer screen. Using C and a PC is straightforward as the screen, keyboard and processor are all interconnected. The basic hooks need to be placed in the program to link the program to the peripherals. When developing a program for the PICmicro® MCU or any microprocessor / microcontroller system, you need not only the software hooks but also the physical hardware to connect the micro to the outside world. Such a system is shown below. 17 DATA ICE PC DATA COMMS TARGET BOARD I/O Using such a layout enables basic I/O and comms to be evaluated, tested and debugged. The use of the ICE, through not essential, speeds up the development costs and engineer’s headaches. The initial investment may appear excessive when facing the start of a project, but time saved in developing and debugging is soon outstripped. The hardware needed to evaluated a design can be a custom made PCB, protoboard or an off the shelf development board such as our PICmicro®MCU Millennium board contains (someone had to do one!). The Millennium board contains all the basic hardware to enable commencement of most designs while keeping the initial outlay to a minimum. Assemble the following hardware in whichever format you prefer. You WILL need a PIC programmer such as the PICSTART Plus as a minimal outlay in addition to the C compiler. A simple program I use when teaching engineers about the PIC is the ‘Press button – turn on LED’. Start with a simple code example – not 2000 lines of code! In Assembler this would be:- main lp1 btfss got bsf btfsc goto bcf goto In C this converts to porta,switch main portb,led porta,switch lp1 portb,led main ;test for switch closure ;loop until pressed ;turn on led ;test for switch open ;loop until released ;turn off led ;loop back to start 18 main() { set_tris_b(0x00); while(true) { if (input(PIN_A0)) output_high(PIN_B0); else output_low(PIN_B0); } } When assembled, the code looks like this:- //set port b as outputs //test for switch closure //if closed turn on led //if open turn off led main() { set_tris_b(0x00); 0007 MOVLW 00 0008 TRIS 6 while(true) { if (input(PIN_A0)) 0009 BTFSS 05,0 000A GOTO 00D output_high(PIN_B0); 000B BSF 06,0 else 000C GOTO 00E output_low(PIN_B0); 000D BCF 06,0 } 000E GOTO 009 } As you can see, the compiled version takes more words in memory – 14 in C as opposed to 9 in Assembler. This is not a fair example on code but as programs get larger, the more efficient C becomes in code usage. 19 20 C Fundamentals This chapter presents some of the key aspects of the C programming language A quick overview of each of these aspects will be given. The goal is to give you a basic knowledge of C so that you can understand the examples in the following chapters. The topics discussed are: Program structure Components of a C program #pragma main #include directive printf statement Variables Constants Comments Functions C keywords 21 1.1 The Structure of C Programs All C program contain preprocessor directives, declarations, definitions, expressions, statements and functions. Preprocessor directive A preprocessor directive is a command to the C preprocessor (which is automatically invoked as the first step in compiling a program). The two most common preprocessor directives are the #define directive, which substitutes text for the specified identifier, and the #include directive, which includes the text of an external file into a program. Declaration A declaration establishes the names and attributes of variables, functions, and types used in the program. Global variables are declared outside functions and are visible from the end of the declaration to the end of the file. A local variable is declared inside a function and is visible form the end of the declaration to the end of the function. Definition A definition establishes the contents of a variable or function. A definition also allocates the storage needed for variables and functions. Expression An expression is a combination of operators and operands that yields a single value. Statement Statements control the flow or order of program execution in a C program. Function A function is a collection of declarations, definitions, expressions, and statements that performs a specific task. Braces enclose the body of a function. Functions may not be nested in C. 22 main Function All C programs must contain a function named main where program execution begins. The braces that enclose the main function define the beginning and ending point of the program. Example: General C program structure #include #define PI 3.142 float area; int square (int r); /* preprocessor directive */ /* include standard C header file */ /* global declaration */ /* prototype declaration */ main() { /* beginning of main function */ int radius_squared; /* local declaration */ int radius = 3; /* declaration and initialization */ radius_squared = square (radius); /* pass a value to a function */ area = PI * radius_squared; /* assignment statement */ printf(“Area is %6.4f square units\n”,area); } /* end of main function & program */ square(int r) { int r_squared; r_squared = r * r; return(r_squared); */ } /* function head */ /* declarations here are known */ /* only to square */ /* return value to calling statement 1.2 Components of a C program All C programs contain essential components such as statements and functions. Statements are the parts of the program that actually perform operations. All C programs contain one or more functions. Functions are subroutines, each of which contains one or more statements and can be called upon by other parts of the program. When writing programs, indentations, blank lines and comments, improve the readability – not only for yourself at a later date, but also for those who bravely follow on. The following example shows some of the required parts of a C program. #include /* My first C program */ main() { printf(“Hello world!”); 23 } The statement #include tells the compiler to include the source code from the file ‘stdio.h’ into the program. The extension .h stands for header file. A header file contains information about standard functions that are used in the program. The header file stdio.h which is called the STandarD Input and Output header file, contains most of the input and output functions. It is necessary to use only the include files that pertain to the standard library functions in your program. /* My first C program / is a comment in C. Tradional comments are preceded by a /* and end with a */. Newer style comments begin with // and go to the end of the line. Comments are ignored by the compiler and therefore do not affect the speed or length of the compiled code. All C programs must have a main() function. This is the entry point into the program. All functions have the same format which is: FunctionName() { code } Statements within a function are executed sequentially, beginning with the open curly brace and ending with the closed curly brace. The curly braces { and } show the beginning and ending of blocks of code in C. Finally, the statement printf(“Hello world!”); presents a typical C statement. Almost all C statements end with a semicolon (;). The end-of-line charater is not recognized by C as a line terminator. Therefore, there are no constraints on the position of statements within a line or on the number of statements on a line. All statements have a semi-colon (;) at the end to inform the compiler it has reached the end of the statement and to separate it from the next statement. Failure to include this will generally flag an error in the NEXT line. The if statement is a compound statement and the ; needs to be at the end of the compound statement: if (ThisIsTrue) DoThisFunction(); 1.3 #pragma 24 The pragma command instructs the compiler to perform a particular action at the compile time such as specifying the PICmicro®MUC being used or the file format generated. #pragma device PIC16C54 In CCS C the pragma is optional so the following is accepted: #device pic16c54 1.4 main() Every program must have a main function which can appear only once. No parameters can be placed in the ( ) brackets which follow. The keyword void may optionally appear between the ( and ) to clarity there are no parameters. As main is classed as a function, all code which follows must be placed within a pair of braces { } or curly brackets. main() { body of program } 1.5 #include The header file, (denoted by a .h extension) contains information about library functions such as what argument(s) the function accepts and what argument (s) the function returns or the location of PICmicro®MCU registers for a specific PIC #include <16C54H> This information is used by the compiler to link all the hardware specifics and source programs together. #include <16c71.h> #include #use rs232(baud=9600,xmit=PIN_B0,rcv=PIN_B1) main() { printf(“Enter characters:”); while(TRUE) putc(toupper(getc())); } The definitions PIN_B0 and PIN_B1 are found in the header file 16C71.H. The function toupper is found in the header file CTYPE.H. Both of these header files 25 must be used in the program so the compiler has essential information about the functions that you are using. Note that many C compilers also require header files for I/O functions like printf and putc. These are built-in functions for the PICmicr®MCU that are pulled in via the #use rs232 and do not require a separate header file. Angled brakets #include tell the preprocessor to look in predefined include file directories for the file, while the quote marks tell the preprocessor to look in the current directory first. #include “thatfile.h” You have probably noticed that the #include directive does not have a semicolon at the end. The reason for this is that the #include directive is not a C statement, but instead is a preprocessor directive to the compiler. The whole of the include file is inserted into the source file at the compile stage. 1.6 printf Function The printf function is a standard library function which allows the programmer to send printable information. The general format for a printf() statement is: printf(“control_string”, argument_list); A control_string is a string with double quotes at each end. Inside this string, any combination of letters, numbers and symbols can be used. Special symbols call format specifiers are denoted with a %. The control_string must always be present in the printf() function. An argument_list may not be required if there are no format specifiers in the format string. The argument_list can be composed of constants and variables. The following two examples show printf() statements using a constant and then a variable. printf(“Hello world!”); printf(“Microchip® is #%d!”,1); The format specifier (%d) is dependent on the type of data being displayed. The table below shows all of the format specifiers in C and the data types they affect. Format Specifiers printf() %c single character 26 %d signed decimal interger %f floating point (decimal notation – must include) %e floating point (exponential or scientific notation) %u unsigned decimal integer %x unsigned hexadecimal integer (lower case) %X unsigned hexadecimal integer (upper case) l prefix used with %d, %u, %x to specify long integer NOTE: A 0 (zero) following a % character within a format string forces leading zeros to be printed out. The number following specifies the width of the printed field. printf(“The Hex of decimal 12 is %02x\n”,12); This would be print out as: The Hex of decimal 12 is 0c Escape Sequences \n \r \’ \\ \? \0 \xhhh newline carriage return single quote backslash question mark null character insert HEX code hhh \t horizontal tab \f formfeed \” double quote %% percent sign \b backspace \v vertical tab The format specification can also be shown as %[flags][width][.precision], so in a previous example the line: printf(“Area is %6.4f square units\n”,area); will print out the value area in a field width of 6, with a precision of 4 decimal places. By default the printf output goes out the last defined RS232 port. The output, however, can be directed to anything defining your own output function. For example: void lcd_putc(char c) { // Insert code to output one // character to the LCD here } printf(lcd_putc, “value is %u”, value); 1.7 Variables 27 A variable is a name for a specific memory location. This memory location can hold various values depending on how the variable was declared. In C, all variables must be declared before they are used. A variable declaration tells the compiler what type of variable is being used. All variable declarations are statements in C and therefore must be terminated with a semicolon. Some basic data type that C supports are char, int, float, and long. The general format for declaring a variable is: type variable_name; An example of declaring a variable is char ch;. The compiler would interpret this statement as the variable ch is declared as a char (8-bit unsigned integer). 1.8 Constants A constants is a fixed value which cannot be changed by the program. For example, 25 is a constant. Integer constants are specified without any fractional components, such as –100 or 40. Floating point constants require the decimal point followed by the number’s fractional component. The number 456.75 is a floating point constant. Character constants are enclosed between single quotes such as ‘A’ or ‘&’. When the compiler encounters a constant in your program, it must decide what type of constant it is. The C compiler will, by default, fit the constant into the smallest compatible data type that will hold it. So 15 is an int and 64000 is an unsigned. A constant can be declared using the #define statement. #define

Top_arrow
回到顶部
EEWORLD下载中心所有资源均来自网友分享,如有侵权,请发送举报邮件到客服邮箱bbs_service@eeworld.com.cn 或通过站内短信息或QQ:273568022联系管理员 高进,我们会尽快处理。