User manual

LPCXpresso Experiment Kit - User’s Guide
Page 34
Copyright 2013 © Embedded Artists AB
Note that registers GPIO0DIR and GPIO0DATA are accessed as LPC_GPIO0->DIR and
LPC_GPIO0->DATA, respectively.
Below is the two statements needed to first set PIO0_2 to an output and then pull the output low. This
will turn the LED on.
// Set PIO0_2 as an output
LPC_GPIO0->DIR = LPC_GPIO0->DIR | (0x1<<2);
// Turn LED1 on = set PIO0_2 pin low, i.e., clear bit
LPC_GPIO0->DATA = LPC_GPIO0->DATA & ~(0x1<<2);
As seen, each of the registers is first read and then bit #2 is manipulated. In the first statement, bit #2
is set which makes PIO0_2 an output. In the second statement, bit #2 is set to zero. This pulls PIO0_2
low.
Note that all bits in the registers must be read and only the bit of interest shall be manipulated. The
shift operation, (0x1<<2), is a good way of writing code. The “<<2” part indicates clearly that it is bit #2
that is manipulated. It is simpler for a reader of the code to quickly see this than to write the constant
value 0x04.
Below is an alternative, more compact way of writing the statements. This is a common way to write
this kind of statements.
// Set PIO0_2 as an output
LPC_GPIO0->DIR |= (0x1<<2);
// Turn LED1 on = set PIO0_2 pin low, i.e., clear bit
LPC_GPIO0->DATA &= ~(0x1<<2);
In real, professional programs, it is common to use defines to hide details about hardware
manipulation. Below is an example of how this can be done.
// Create defines for simpler access of LED1
#define DIR_REG_LED1 LPC_GPIO0->DIR
#define DATA_REG_LED1 LPC_GPIO0->DATA
#define PIO_PIN_LED1 2
#define LED1_ON DATA_REG_LED1 &= ~(1<<PIO_PIN_LED1)
#define LED1_OFF DATA_REG_LED1 |= (1<<PIO_PIN_LED1)
// Set PIO0_2 as an output
DIR_REG_LED1 |= (0x1<<PIO_PIN_LED1);
// Turn LED1 on
LED1_ON;
It is possible to take the principles further and create general macros for handling all ports and pins.
This was just an example of how to create well-structured, maintainable and professionally looking
code.
Chapter 9 contains a description how to get started with the LPCXpresso IDE. Read this chapter and
follow the guide how to import the projects. Start working with project “lab 1a”, which is the base for
this first experiment.
After compiling and linking without errors, follow the guide how to download and run the project.
In embedded programming it is important to have full control over the variables, more specifically the
number range they can hold. The original C standard was a little vague on the number of bits different
variable types have. It is specified as “at least X number of bits” and there is a specified order between
different types. However in embedded programming the exact number of bits is important to keep track
of. Therefore it is common to have an include file that have created/specified new variable types with
the number of bits exactly specified. We will use this setup in all experiments.