Speed up by using registers

Hi,
I want to make a simple state analyzer with a MEGA2560. The lower 3 bits of Port K shall be recorded with following sketch:

#include <avr/io.h>

#define MAX_SIZE (1000)

uint8_t regA, regB;
uint8_t dat[MAX_SIZE];
uint16_t idx = 0;
uint8_t vcnt = 0; // repeat counter
uint8_t *ptdat = dat;

void setup(void) {
  pinMode(A8, INPUT);
  pinMode(A9, INPUT);
  pinMode(A10, INPUT);

  regA = (PORTK & 7); // lower 3 bits
}

void loop(void)
{
  if (idx < MAX_SIZE) {
    regB = (PORTK & 7);
    if (regB == regA) {
      if (vcnt < 31) vcnt++;
      else {
        *ptdat = regB | 248; // 31<<3 to upper 5 bits
        ptdat++;
        vcnt = 0;
        idx++;
      }
    }
    else {  // new value
      *ptdat = regB | (vcnt << 3);
      ptdat++;
      vcnt = 0;
      idx++;
      regA=regB;
    }
  }
}

With this code the compiler generates all variables in RAM.
To speed up the code regA, regB, idx, vcnt, and *ptdat could be placed into registers of the controller.

Is this possible without coding in assembler?

You make all variables global so that you force them into memory. The compiler only can (and will) use copies in registers if that helps.

Do you have local variables at all, with reduced life time? Then mark these variables register.

ok, I'll check this.

I do not know.

At a glance it looks like you are doing some calculations that don’t need to be done as you are grabbing the data.

Just grab the data, stash it, then after you get all the samples loop over them and do the bit twiddling.

a7

Yes.

Wrap the code in loop in an infinite loop (while (true)). Make all your data local to loop. After those changes it is very unlikely that hand-coded assembly will be better than what the compiler generates.

You probably want PINK rather than PORTK…

The devil made me do it.

image