1

Is there a more efficient and cleaner way of doing what the following method is already doing?

void sendCode(prog_uint16_t inArray[], int nLimit) {

  unsigned int arr[nLimit];
  unsigned int c;
  int index = 0;

  while ((c = pgm_read_word(inArray++))) {
    arr[index] = c;
    index++;
  }

  for (int i = 0; i < nLimit; i=i+2) {
    delayMicroseconds(arr[i]);
    pulseIR(arr[i+1]);
  }

}

This is in reference to an existing question I had answered.

Arduino - Iterate through C array efficiently

1 Answer 1

2

There should be no need for the local arr array variable. If you do away with that you should both save temporary stack space and speed up execution by removing the need to copy data.

void sendCode(const prog_uint16_t inArray[]) {
  unsigned int c;

  for (int i = 0; c = pgm_read_word(inArray++); i++) {
    if (i % 2 == 0) { // Even array elements are delays
      delayMicroseconds(c);
    } else {          // Odd array elements are pulse lengths
      pulseIR(c);
    }
  }
}

This code assumes that the maximum integer stored in an int is greater than the maximum size of inArray (this seems reasonable as the original code essentially makes the same assumption by using an int for nLimit).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that, looks like it's working fine. It saves space as I can remove the nLimit that's passed to each method. The only modification I had to make was that sendCode() should take const prog_uint16_t inArray[].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.