Arduino - Optimising existing method for iterating through an array

帅比萌擦擦* 提交于 2020-01-15 11:23:06

问题


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:


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).



来源:https://stackoverflow.com/questions/8966760/arduino-optimising-existing-method-for-iterating-through-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!