GPIO registers and port manipulation

Post your cool example code here.
atacanteknik
Posts: 4
Joined: Mon May 08, 2017 4:23 am

Re: GPIO registers and port manipulation

Post by atacanteknik » Tue May 09, 2017 12:50 pm

how i add on integer port read like that

int state = DDRC & B00000011;

and write
DDRC = state | (bx<<5) | (by<<2);

edogaldo
Posts: 250
Joined: Fri Jun 03, 2016 8:19 am

Re: GPIO registers and port manipulation

Post by edogaldo » Tue May 09, 2017 8:11 pm

atacanteknik wrote:how i add on integer port read like that

int state = DDRC & B00000011;

and write
DDRC = state | (bx<<5) | (by<<2);
DDRx is the data direction register in AVRs; DDRx+PORTx in AVRs are almost the equivalent of GPIOx_CRH/CRL in STMs; details on how they work are specified in previous posts of the thread and in the related reference manuals.

dannyf
Posts: 43
Joined: Wed May 11, 2016 4:29 pm

Re: GPIO registers and port manipulation

Post by dannyf » Fri Jun 16, 2017 12:06 am

atacanteknik wrote:how i add on integer port read like that
it depends on your coding style.

I used a set of routines across 8/16/32-bit families.

Code: Select all

#define IO_SET(port, pins)  port |= (pins)  //set pins on port
#define IO_CLR(port, pins)  port &=~(pins)  //clear pins on port
#define IO_FLP(port, pins)  port ^= (pins)  //flip pins on port
#define IO_GET(port, pins) ((port) & (pins))  //read pins on port
so in your example, it would be something like this:

Code: Select all

  if (IO_GET(BTN_PORT, BTN)) IO_SET(RELAY_PORT, RELAY0);
  else IO_FLP(RELAY_PORT, RELAY1);
if BTN reads high, it set RELAY0;
if BTN reads low, it flips RELAY1.

Once you implement a set of routines like that on your target chip, your user code would compile and work as expected, making it immensely portable and debug much easier.

Ollie
Posts: 161
Joined: Thu Feb 25, 2016 7:27 pm

Re: GPIO registers and port manipulation

Post by Ollie » Fri Jun 16, 2017 8:57 am

If your application is using interrupts that could manipulate the target GPIO ports, the read-modify-write operation is not safe. That is the reason, why STM has designed BSRR registers to set and reset selected pins.

The monotonic pin manipulations can be done with macros

#define gpio_clear(GpioPort, GpioPins) GpioPort->BSRR = ((GpioPins) << 16)
#define gpio_set(GpioPort, GpioPins) GpioPort->BSRR = (GpioPins)

These are the fastest way to do GPIO pin updates.

Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest