When any programmer deals with code that is large and complex, some simplification is required when dealing with multiple quantities of functions, variables and statements. With the help of macros on C, a pin or a constant value can be defined once and then reutilize it over and over. Need to do a modification of the value of the macro? Just change once and it is reflected immediately in the rest of the code. In other words, is a useful shortcut. In this short tutorial, check out how to implement this very useful feature.
Table of Contents
Syntax of Macros
Macros consists in 3 parts. First, the word #define is placed in a new sentence. Afterwards, the label or name of it. Finally, the text is piece or argument to be replaced by the label.
#define label text
Example of Macros
Example 1: Constants
A common use for Macros is defining constants, such as math, frequency clocks, data, etc. For example:
#define clock 4000000
And it could be used this way:
int time=1/clock;
Example 2: Pins
Instead of using the pins of a microcontroller as they are named exactly, call them instead with the help of a Macro. If the main advantage is the simplicity, the secondary advantage is easiness to be reassigned in case the pin needs to change; the rest of the code is left unchanged! The following example is extracted from a tutorial about How to drive 7-Segment Displays with a 8-bit PIC.
//Macros for the 7-segment display #define f PORTAbits.RA2 #define g PORTCbits.RC0 #define a PORTCbits.RC1 #define b PORTCbits.RC2 #define e PORTCbits.RC3 #define d PORTCbits.RC4 #define c PORTCbits.RC5
To use this shortcut, just call it by the label.
f=1;
Resources
- Macros. MPLab Developer Help. Link.
techZorro's Index of Content
Keep Reading!
- Macros on C, how to create useful Aliases for the CodeMacros are tremendously helpful in saving time and clutter in code writing. This tutorial includes tutorials on C. Click here to read.
- Switch in C, the neat multiple decision maker in Control FlowIn Control Flow, Switch replaces multiples if's and merges into one elegant decision making solution. Click here to read.
- While loop in C language, the ‘ask first' of Control FlowWhile in C is great for creating loops using Control Flow. It's great for repeated tasks and counters! Click here to read more.
- Code Template, an easy guide for PIC Microcontrollers in CWriting a program with order is a time saver. Download today the code template for PIC microcontrollers for free. Click here to read more.
- Functions in C Programming LanguageFunctions lets you reutilize code efficiently and opens up libraries done by others. Click here to learn to use functions in C.