Direct GPIO Pin State Reads

Overview

There are times when you will need to read the state of a pin regardless of how it has been configured - SPI, input, output, I2C, UART, etc. in a way that is independent from the mbed SDK's DigitalIn or DigitalOut methods. In this case, it is useful to understand the registers and memory map of the MCU you are using, since usually the pin state will be reflected in one of these registers. In this notebook, I will be compiling the method to do this in one convenient location, whenever I work out how to do it on a particular MCU. I am not going to be too wordy, instead I will be relying on code examples and code comments, as I believe readers will be able to glean the required information easily and quickly this way.

NXP MCUs

LPC11U24

mbed way

DigitalIn inPin(p6);
int i;

i = inPin;

If you look up the pin mapping on the mbed LPC11U24 board schematic, you will find that it maps onto pin PIO0.8 on the LPC11U24FBD64/401 chip. So it access it, we will need to access GPIO Port 0, bit 8 of potentially 0..31 (note that not all the 32 bits in a port register may be usable, depending on whether they have been defined on your MCU or not). On the other hand, if you needed to access a pin on Port 1, such as PIO1.0, then you would need to use LPC_GPIO->PIN[1] instead of LPC_GPIO->PIN[0] in the example below.

Direct register access way

int i = (LPC_GPIO->PIN[0] & (1UL << 8));

LPC1768

The same thing for the LPC1768 is done similarly, but slightly differently due to differences in the register definitions.

Direct register access way

int i = (LPC_GPIO0->FIOPIN & (1UL << 8));

Other MCUs

Haven't worked it out yet for other MCUs, but if you have, please do drop a comment and I will be sure to add them in here. I do have a Freescale FRDM-KL25Z board and a couple of ST Micro Nucleos on hand, but I have yet to try this "trick" on those boards.


Please log in to post comments.