Short introduction to C for AVR

Similar documents
Embedded Systems. Introduction. The C Language. Introduction. Why C instead ASM. Introduction to C Embedded Programming language

Variables and literals

C Language Programming

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Fundamental of Programming (C)

A Fast Review of C Essentials Part I

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

EL6483: Brief Overview of C Programming Language

Programming for Engineers Introduction to C

The C Programming Language Guide for the Robot Course work Module

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

INTRODUCTION 1 AND REVIEW

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Review of the C Programming Language for Principles of Operating Systems

C: How to Program. Week /Mar/05

EL2310 Scientific Programming

BLM2031 Structured Programming. Zeyneb KURT

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Have examined process Creating program Have developed program Written in C Source code

Course Outline Introduction to C-Programming

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Technical Questions. Q 1) What are the key features in C programming language?

Full file at

If you note any errors, typos, etc. with this manual or our software libraries, let us know at

UNIT- 3 Introduction to C++

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Chapter 2 - Introduction to C Programming

CS201 Some Important Definitions

Flow Control. CSC215 Lecture

Review of the C Programming Language

ME 461 C review Session Fall 2009 S. Keres

Introduction to C Final Review Chapters 1-6 & 13

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

Lecture 2: C Programming Basic

printf( Please enter another number: ); scanf( %d, &num2);

Work relative to other classes

CSCI 171 Chapter Outlines

CENG 447/547 Embedded and Real-Time Systems. Review of C coding and Soft Eng Concepts

Chapter 2, Part I Introduction to C Programming

Fundamentals of Programming

Embedded programming, AVR intro

Introduction to C Language

2 nd Week Lecture Notes

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

The C++ Language. Arizona State University 1

C Language, Token, Keywords, Constant, variable

Arduino Uno. Power & Interface. Arduino Part 1. Introductory Medical Device Prototyping. Digital I/O Pins. Reset Button. USB Interface.

Chapter 2: Basic Elements of C++

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Fundamentals of Programming. Lecture 3: Introduction to C Programming

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Topic 6: A Quick Intro To C

Full file at C How to Program, 6/e Multiple Choice Test Bank

Creating a C++ Program

Chapter 12 Variables and Operators

Function Call Stack and Activation Records

Short Notes of CS201

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Objectives. In this chapter, you will:

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

C++ Programming: From Problem Analysis to Program Design, Third Edition

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

Pace University. Fundamental Concepts of CS121 1

CS201 - Introduction to Programming Glossary By

Model Viva Questions for Programming in C lab

CS16 Exam #1 7/17/ Minutes 100 Points total

CHW 469 : Embedded Systems

Special Topics for Embedded Programming

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

6.096 Introduction to C++ January (IAP) 2009

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

CS Programming In C

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Tutorial No. 2 - Solution (Overview of C)

Lecture 5: C programming

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

Chapter 1 & 2 Introduction to C Language

LESSON 6 FLOW OF CONTROL

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Fundamentals of Programming Session 4

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

CMPE-013/L. Introduction to C Programming

Programming, numerics and optimization

Some Basic Concepts EL6483. Spring EL6483 Some Basic Concepts Spring / 22

3 The L oop Control Structure

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Quick Reference Guide

Programming in C and C++

Why embedded systems?

>B<82. 2Soft ware. C Language manual. Copyright COSMIC Software 1999, 2001 All rights reserved.

Transcription:

Short introduction to C for AVR (http://winavr.scienceprog.com/short-introduction-to-c), (www.smileymicros.com), (https://ccrma.stanford.edu/wiki/avr_programming#anatomy_of_a_c_program_for_avr) (AVR035: Efficient C Coding for AVR) This is a very basic overview of the essential parts of the C language that are frequently encountered when writing simple programs for the AVR. It is obviously impossible to thoroughly cover the C language in a few pages, but this should provide a brief explanation of most things that will be encountered in demo programs. C language is a function based programming language. C program itself is a function. Usually parameters to C function are passed as arguments. A function consists of a name followed by the parentheses enclosing arguments or an empty pair of parentheses if there are not arguments required. If there are several arguments, they are separated by commas. The mandatory part in a C program is main function. This function must be included in every program because this is the first function which is run after the execution of program. Let s take an example: /**************** #include <stdio.h> int main(void) //main function printf( Hello world!\n ); return 0; /**************** This is a very basic C program, but it contains all necessary elements. Let s examine a little bit what we have written here... #include <stdio.h> - is a preprocessor command. All preprocessor commands are identified by # sign at the beginning of the line. #include command tells the preprocessor to open file stdio.h and from it necessary stored parts while compiling program. The file name is surrounded by brackets <>. Bracket marks <> tell the preprocessor to search for the file in the region defined by operating system variables (for instance path variable in Environment variables). If double quotes are used instead of bracket marks, then file searching is done only in the default directory of the project. Next line is int main(void). It is always necessary to define the type of function return and of course a function has an argument. The type int shows that main function returns an integer and no arguments to the function is needed. An opening brace indicates the beginning of a block of sentences. One of those sentences is printf(). This function is taken from stdio.h library and writes a message to the computer terminal (this case screen). Return 0 is a returning parameter to the function. And every function should end with a closing brace. /* is commenting the line. This means that the line marked with /* is not included in compilation. Preprocessor You maybe don't know or probably didn't think about this but you are using program preprocessing before compiling it. As I said before compiling I mean, that each time you are compiling your project, the C compiler prepares the program file to be ready for compilation. The Preprocessor includes other files to main file, defines symbol constants and macros, prepares conditional compilation of code. All preprocessor tasks are marked with ampersand symbol #. Let s go through most of the directives of a preprocessor: 1

#include One and common directive is #include. You have already noticed, that you use this directive to include external c files and headers to your project. You can use #include in two ways: #include <filename> #include filename The difference between them is where preprocessor will be looking for these files. If < > are used then the preprocessor will be looking for the standard library if then preprocessor will look in default project folder or location defined in the makefile. #define #define is a second important directive which allows for the creation of constants and macro commands. The manner in which the define command is used: #define identifier value When a constant or macro command is defined, then in any place where Identifier is used it will be changed to the defined value. For instance #define PI 3.14159 Then in the program the PI value will be replaced by 3.14159. This allows for controlling values very easily. It could be some particular constants, port address definitions. And of course the usage of good nomenclature of identifiers makes the program more readable and descriptive. #define can also be used to define macro commands. The following example will clear things out: #define CIRCLE_AREA(x) (PI*(x)*(x)) Each time when in the program CIRCLE_AREA(x) will be used, identifier will be replaced with its value like: area=circle_area(4); will be replaced by: area=(3.14159*4*4); What is the benefit of this? First of all, when regular functions are used, then the program calls them from a specific address. When we use macro commands, functions are inserted in-line. Sometimes it may speed up the program. Opposite to #define directive is #undef directive which removes the previous definition of constant or macro. Function prototypes give the name, arguments and return type of functions that will be used later in the program. They can be included in header files or in the.c file before the function is defined. int checkbutton(int whichbutton); void setled(int whichled, int on); Variables in C language What are variables in C language. Variables are simple keywords which are defined by the values. Values can be changed. Variables are like boxes with some size where values like apples can be put in. So variables can have various forms and sizes, so called variable types. A variable type is defined by a reserved word which indicates the type and size of the variable identifier: unsigned char my_char; long all_my_numbers; int number; Why do we need variables? The basic answer is that memory is limited and the compiler needs to know how much space to reserve for each variable. So the programmer needs to specify the variable type and its size by using one of reserved words from the table: 2

Type Short version Size Domain unsigned char uint8_t 8-bit, 1 byte 0 do 255 char int8_t 8-bit, 1 byte -128 do +127 unsigned int uint16_t 16-bit, 2 byte 0 to 65,535 int int16_t 16-bit, 2 byte -32,768 do +32,767 unsigned long uint32_t 32-bit, 4 byte 0 to 4,294,967,295 long int32_t 32-bit, 4 byte -2,147,483,648 do +2,147,483,648 long long int64_t 64-bit, 8 byte 9,22*10-18 do 9,22*10 18 unsigned long long uint64_t 64-bit, 8 byte 0... 1,844*10 19 float 32-bit, 4 byte ±1.175e-38 do ±3.402e38 double 32-bit, 4 byte ±1.175e-38 do ±3.402e38 Few statements demonstrating the usage of variables and value assignments: int i; /* Define a global variable i */ i = 1; /* Assign i the value 0 */ /* Begin new block of sentences */ int i; /* Define a local variable i */ i = 2; /* Set its value to 2 */ // Close block /* Here is again 1 from the outer block */ volatile int I; // A global variable should be defined as volatile, if its value may be changed between consecutive statements. Arrays Arrays are adjacent chunks of memory of the same size that allow convenient indexing. They are defined as follows: uint8 myarray[5]; // define an array of 5 unsigned 8-bit integers uint8 myarray2[3] = 10, 12, 18; // define an array of 3 unsigned 8-bit integers and initialize their values to 10, 12 and 18 Arrays can be accessed for assignment or use in expressions with square brackets as well. Note that array indices begin at 0: myarray2[0] = 11; // assign the value 11 to the first element of the array myarray2 myarray2[1] = myarray[0]; // assign the value of the first element of myarray to the second element of myarray2 Constant Constant value is understood as a non-changeable value like PI=3.141592... value in math. Usually you use constants in your programs, but don't realize that they are constants. For instance: 3

x=x+3; The number 3 is a constant which will be compiled directly in an addition operation. Constants can be characters or strings. Like in function printf( Hello World\n ); Hello World is a string constant which is placed in the program memory and will never changes. It is usually recommended to declare constants by using an identifier with reserved word const: const int No=44; Identifying the variable as constant will cause the compiler to store this variable in the program memory rather than in RAM, thus saving space in RAM. If special functions are used, then constants can be also stored in EEPROM memory. Numeric constants can be declared in many ways indicating their base. Decimal integer constants (base 10) consist of one or more digits, 0 through 9, where 0 cannot be used as the first digit. Binary constants (base 2) begin with a 0b or 0B prefix, followed by one or more binary digits (0, 1). Octal constants (base 8) consist of one or more digits 0 through 7, where the first digit is 0. Hexadecimal constants (base 16) begin with a 0x or 0X prefix, followed by a hexadecimal number represented by a combination of digits 0 through 9, and characters A through F. Floating-point constants consist of: o an optional sign - or +; o an integer part a combination of digits 0 through 9; o a period; o a fractional part a sequence of digits 0 through 9; o an optional exponent e or E, followed by an optionally signed sequence of one or more digits For example, the following floating-point constant contains both the optional and required parts: +1.15e- 12. A character constant can be represented as a character in quotation marks like 't' or as character code like '\x74'. Backslash may confuse compiler. Let s say you want to assign a backslash as a character then you should write like this '\\'. Functions A function is defined as: returntype FunctionName(arg1type arg1name, arg2type arg2name...) declarations statements A function definition specifies what the function does, and can occur in a few different places. Functions can be defined after the main function, as long as a function prototype has first been declared. The prototype contains the name, return type and arguments, but not the body of the function. Here, the term declaration is used for function prototypes that declare that the function exists. The term definition is used where the body of the function is actually specified. Normally, a.c file has a companion.h file that contains all the function prototypes. With the AVRlib, we normally use a number of.c files (e.g. timer.c or a2d.c) that contain function definitions. The.c files are compiled together with the.c file you write, and are specified in the makefile (see below). But, in order to use functions from those.c files, you first need to declare their prototypes. This is done by including the corresponding.h file (e.g. timer.h or a2d.h). Look in an.h file in the AVRlib to see what it looks like. Functions can also be defined before the main function, but this is generally considered bad style. After a function is declared, it can be "called" or used, as long as its definition exists. If the function does not return a value, its return type is declared as void. Void is also used if there are no arguments. The example program in the first section contains such a function: 4

void checkbutton(void) The code inside the function is executed when it is "called" from another function: checkbutton(); If the function returns a value, the keyword return must be present in the function, followed by the value to be returned. Once return is reached, the function exits and evaluates to the return value. If a function has arguments, they are normally passed as a value in parentheses after the function name in the function call. Inside the function, the arguments act like variables that have the value that has been passed. Take the following program for example: uint16 timesten(uint16 foo); // function prototype int main(void) uint16 bar; // declare an unsigned 16-bit variable bar = timesten(9);// call the function timesten with the argument 9, store the result in bar uint16 timesten(uint16 foo) //define the function timesten, takes 1 argument return (foo * 10); //return the argument multiplied by 10 Here the variable bar will end up with the value 90. You'll notice that the main function normally has a return type int, and returns a value of 0. This is mainly used as a convention for our purposes. A return value of zero typically indicates that a program has exited normally, and other numbers are used to specify different errors. The main function does not require a prototype. Program Flow Program Flow and control is a control method of your program. For example Loop constructions control the repeated execution of repeated program segments where control is taken by a control parameter. In this article we will go through if/else switch/case statements and loop sentences like while, do while, for. While statement As I mentioned there are three looping sentences available in C language, one of them is While sentence. Let s take an example: #include <stdio.h> int main(void) int guess, i; i=1; guess=5; while (guess!=i) i=guess; guess=(i+(10000/i))/2; printf( Square root of 10000 is %d\n, guess); return 0; While(guess!=i) invokes a looping operation. This causes the statement to be executed repeatedly; always at the beginning, the condition guess!=i is checked. As long the argument is TRUE the while sentence will be 5

continued continuously. When guess becomes equal to I, the while statement will be skipped. I am not going to go deep in to it as there are tons of information about basic C. For Loop If we don t know how many times the loop should be executed, we use a while sentence, but when we know exactly how many times we need to execute a sentence, there is another loop sentence for(s1;s2;s3). For construct takes 3 arguments each separated by semicolons. Without any theories let s see an example: for (i = 0; i < 5; i++) printf("value of i"); 1. The for loop has four components; three are given in parentheses and one in the loop body. 2. All three components between the parentheses are optional. 3. The initialization part is executed first and only once. 4. The condition is evaluated before the loop body is executed. If the condition is false then the loop body is not executed. 5. The update part is executed only after the loop body is executed and is generally used for updating the loop variables. 6. The absence of a condition is taken as true. 7. It is the responsibility of the programmer to make sure the condition is false after certain iterations. Do While sentence Do while is somehow similar to while, just one difference is that there testing of conditions is done after execution of first loop: do printf(" the value of i is %d\n", i); i = i + 1; while (i<5) so 1. The loop body is executed at least once. 2. The condition is checked after executing the loop body once. 3. If the condition is false then the loop is terminated. 4. In this example, the last value of i is printed as 5. If Else Statement if(expression) statement1 else statement2 Let s consider a fragment of program: while((c=getchar())!=eof) if(c>'0'&&c<'9') n++; else n--; I bet there is no need of explanation. Simply if the first part is true then first sentence is executed else other sentence is executed. Other case is with if else if sentence structure: 6

... if (condition 1) simple or compound statement // s1 else if (condition 2) simple or compound statement // s2 else if ( condition 3) simple or compound statement // s3 else if ( condition n ) simple or compound statement // sn Note the increment and decrement operators, ++ and -. The keyword if is followed by an expression in parentheses that evaluates to a number. If the expression evaluates to a number other than zero, then the statements in braces immediately following are evaluated. If the expression evaluates to 0, anything following the else in braces will be evaluated. If there are no braces, then only the next line will be evaluated. An if does not need to be followed by else: you may only want something to be done in one case of the condition, and not in others. The conditional expression normally has a relational operator. The relational operators take two arguments and evaluate to 1 if the relation is true and 0 if it is false. Remember that: 1. You can use if-else if when you want to check several conditions but still execute one statement. 2. When writing an if-else if statement, be careful to associate your else statement to the appropriate if statement. 3. You must have parentheses around the condition. 4. You must have a semicolon or right brace before the else statement. Switch statement switch (expressions) case constant expressions For example: switch (i/10) case 0: printf ("Number less than 10"); // A break; case 1: printf ("Number less than 20"); // B break; case 2: printf ("Number less than 30"); // C break; default: printf ("Number greater than or equal to 40"); // D break; Remember that: 1. The switch expression should be an integer expression and, when evaluated, it must have an integer value. 2. The case constant expression must represent a particular integer value and no two case expressions should have the same value. 3. The value of the switch expression is compared with the case constant expression in the order specified, that is, from the top down. 7

4. The execution begins from the case where the switch expression is matched and it flows downward. 5. In the absence of a break statement, all statements that are followed by matched cases are executed. So, if you don't include a break statement and the number is 5, then all the statements A, B, C, and D are executed. 6. If there is no matched case then the default is executed. You can have either zero or one default statement. 7. In the case of a nested switch statement, the break statements break the inner switch statement. 8. The switch statement is preferable to multiple if statements. Arithmetic Operators, Data Access and Size Operators, Miscellaneous Operators, Logical and Relational Operators, Bitwise Operators, Assignment Operators, Operator Precedence and Associativity in C. The main thing that microcontrollers do is operate with data. There are four main operations that a microcontroller does: adds, abstracts, multiplies and divides (+,-,*,/). Division can be split into division / and modulus operation %. For instance i1/i2 is integer division. Another group of operators includes Relation operators. They are used for boolean conditions and expressions. Expressions with these operators return true or false values. Zero is taken as false and non zero value as true. Operators may be as follows: <, <=, > >=, ==,!=. 8

Note the difference between the equality operator == and the assignment operator =. This is one of the most common sources of bugs in C programming. AND OR XOR 0 & 0 = 0 0 0 = 0 0 ^ 0 = 0 0 & 1 = 0 0 1 = 1 0 ^ 1 = 1 1 & 0 = 0 1 0 = 1 1 ^ 0 = 1 1 & 1 = 1 1 1 = 1 1 ^ 1 = 0 9

The _BV Macro In the C language one assigns and tests bits using bit operators, the assign operator, and the concept of bit masks: PORTC = 0x01; // Set bit 0 only. PORTC &= ~0x01; // Clear bit 0 only. PORTC ^= 0x01; // Toggle bit 0 only. PORTC & 0x01; // Test bit 0 only. PORTC = 0x80; // Set bit 7 only. Using macros makes this easier to read. The _BV() macro in avr-libc takes a number as the argument and converts it to the appropriate bit mask. (The BV stands for Bit Value). The _BV() macro is defined as: #define _BV(x) (1 << x) this allows: PORTC = _BV(0); // Set bit 0 only. PORTC &= ~(_BV(1)); // Clear bit 1 only. PORTC ^= _BV(7); // Toggle bit 7 only. This can be further enhanced with the defines found in the processor header files: // For atmega128 #include <avr/io.h> UCSR0B = _BV(TXEN0); // Set bit 3 in UCSR0B only. Using bit operators, one can do multiple, non-contiguous bits at a time: PORTC = (_BV(0) _BV(2) _BV(7)); // Set bits 0,2,7 PORTC &= ~(_BV(1) _BV(2) _BV(6)); // Clear bits 1,2,6 PORTC ^= (_BV(5) _BV(3)); // Toggle bits 3,5 The symbol between each _BV macro statement means logically OR. (_BV(0) _BV(2) _BV(7)); logically OR s the bits together e.g Name bit7 bit6 bit5 bit4 bit3 bit2 bit bit0 _BV(0) = 0 0 0 0 0 0 0 1 _BV(2) = 0 0 0 0 0 1 0 0 _BV(7) = 1 0 0 0 0 0 0 0 or ed = 1 0 0 0 0 1 0 1 A further example is: UCSRB = _BV(TXEN) _BV(RXEN) _BV(RXCIE); /* tx/rx enable, rx complete*/ 10

Access to Port All Port the AVR microcontrollers are controlled via registers. DDRx PINx PORTx Data directions register for PORTx. x corresponds to A, B, C, D etc. (dependent on the amount of the Port of the used AVR). Bit in the register set (1) for output, bit deleted (0) for input. Input address for PORTx. Condition of the Port. The bits in PINx correspond to the condition of the Port pins defined as input. Bit 1 if pin high, bit 0 if Port pin low. Data pointer for PORTx. This register is used, in order to head for the outputs of a Port. With pins, which were switched by means of DDRx to input, the internal Pull UP of resistors can be activated or deactivated over PORTx (1 = actively). Example program for AVR /* * blinky_port_a.c */ #define F_CPU 16000000ul // definition of fxtal for CPU in Hertz, ul - unsigned long #include <avr/io.h> // Standard AVR header #include <util/delay.h> // Delay loop functions int main(void) DDRA = 0xFF; // PORTA is output while (1) for (int i=1; i<=128; i*=2) PORTA = i; _delay_ms(10); for (int i=128; i>1; i/=2) PORTA = i; _delay_ms(10); // end while //delay for 10ms Efficient Use of Variables A C program is divided into many functions that execute small or big tasks. The functions receive data through parameters and may also return data. Variables declared inside a function are called local variables. Variables declared outside a function are called global variables. Variables that are local, but must be preserved between each time the function is called, must be declared as static local variables. Global variables that are declared outside a function are assigned to an SRAM memory location. The SRAM location is reserved for the global variable and cannot be used for other purposes, this is considered to be waste of valuable SRAM space. Too many global variables make the code less readable and hard to modify. Local variables are preferably assigned to a register when they are declared. The local variable is kept in the same register until the end of the function, or until it is not referenced further. Global variables must be loaded from the SRAM into the working registers before they are accessed. Macros vs. Functions Functions that assemble into 3-4 lines of assembly code or less can in some cases be handled more efficiently as macros. When using macros the macro name will be replaced by the actual code inside the macro at compile time. For very small functions the compiler generates less code and gives higher speed to use macros than to call a function. 11

Interrupt Routines When entering an interrupt routine all registers used in the interrupt routine are pushed on the Stack. To reduce code size and optimize speed the interrupt routines should be small and preferably without calls to other functions. The reason is that when the routine calls an external function, the compiler pushes all registers on the Stack. Eighteen Hints to Reduce Code Size 1. Compile with full size optimization. 2. Use local variables whenever possible. 3. Use the smallest applicable data type. Use unsigned if applicable. 4. If a non-local variable is only referenced within one function, it should be declared static. 5. Collect non-local data in structures whenever natural. This increases the possibility of indirect addressing without pointer reload. 6. Use pointers with offset or declare structures to access memory mapped I/O. 7. Use for(;;) for external loops. 8. Use do while(expression) if applicable. 9. Use descending loop counters and pre-decrement if applicable. 10. Access I/O memory directly (i.e., do not use pointers). 11. Declare main as C_task if not called from anywhere in the program. 12. Use macros instead of functions for tasks that generates less than 2-3 lines assembly code. 13. Reduce the size of the Interrupt Vector segment (INTVEC) to what is actually needed by the application. Alternatively, concatenate all the CODE segments into one declaration and it will be done automatically. 14. Code reuse is intra-modular. Collect several functions in one module (i.e., in one file) to increase code reuse factor. 15. In some cases, full speed optimization results in lower code size than full size optimization. Compile on a module by module basis to investigate what gives the best result. 16. Optimize C_startup to not initialize unused segments (i.e., IDATA0 or IDATA1 if all variables are tiny or small). 17. If possible, avoid calling functions from inside the interrupt routine. 18. Use the smallest possible memory model. Five Hints to Reduce RAM Requirements 1. All constants and literals should be placed in Flash by using the Flash keyword. 2. Avoid using global variables if the variables are local in nature. This also saves code space. Local variables are allocated from the stack dynamically and are removed when the function goes out of scope. 3. If using large functions with variables with a limited lifetime within the function, the use of subscopes can be beneficial. 4. Get good estimates of the sizes of the software Stack and return Stack (Linker File). 5. Do not waste space for the IDATA0 and UDATA0 segments unless you are using tiny variables (Linker File). Checklist for Debugging Programs 1. Ensure that the CSTACK segment is sufficiently large. 2. Ensure that the RSTACK segment is sufficiently large. 3. Ensure that the external memory interface is enabled if it should be enabled and disabled if it should be disabled. 4. If a regular function and an interrupt routine are communicating through a global variable, make sure this variable is declared volatile to ensure that it is reread from RAM each time it is checked. 12