Arduino: почему эти два цикла дают разные результаты? - PullRequest
0 голосов
/ 31 января 2020

Я столкнулся со странной проблемой. Насколько мне известно, эти две части кода Arduino должны давать одинаковый результат, но это не так. Я вставлю весь эскиз Arduino, а затем вставлю две части кода, которые ведут себя таким образом.

averageValue1 и averageValue2 должны вычислять среднее значение за последние 5 чтений с двух потенциометров.

По какой-то причине, когда я вычисляю значение ОБА переменных в одной for-l oop, эти два значения влияют друг на друга. Это означает, что чем выше среднее значение2, тем выше среднее значение1. Однако, если я вычислю две переменные в двух отдельных циклах for, результат будет правильным, и значения, кажется, не влияют друг на друга.

Я почти уверен, что это изменение в коде не должно повлиять на результат, но может кто-нибудь сказать, пожалуйста, почему это происходит?

Это всего набросок кода:

    /*
  Analog input, analog output, serial output

  Reads an analog input pin, maps the result to a range from 0 to 255
  and uses the result to set the pulsewidth modulation (PWM) of an output pin.
  Also prints the results to the serial monitor.

  The circuit:
   potentiometer connected to analog pin 0.
   Center pin of the potentiometer goes to the analog pin.
   side pins of the potentiometer go to +5V and ground
   LED connected from digital pin 9 to ground

  created 29 Dec. 2008
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

*/

// These constants won't change.  They're used to give names
// to the pins used:
const int analogInPin1 = A0;  // Analog input pin that the potentiometer is attached to
const int analogInPin2 = A1;  // Analog input pin that the potentiometer is attached to
const int analogInPin3 = A2;  // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue1 = 0;        // value read from the pot
int sensorValue2 = 0;        // value read from the pot
int sensorValue3 = 0;        // value read from the pot

int outputValue1 = 0;        // value output to the PWM (analog out)
int outputValue2 = 0;        // value output to the PWM (analog out)
int outputValue3 = 0;        // value output to the PWM (analog out)

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
}

int averageCount = 5;
int lastFiveValues1 [5];
int lastFiveValues2 [5];
int averageValue1;
int averageValue2;

void loop() {

  // read the analog in value:
  sensorValue1 = analogRead(analogInPin1);
  sensorValue2 = analogRead(analogInPin2);
  sensorValue3 = analogRead(analogInPin3);


  // map it to the range of the analog out:
  outputValue1 = map(sensorValue1, 0, 1023, 140, -140);
  outputValue2 = map(sensorValue2, 0, 1023, 140, -140);
  outputValue3 = map(sensorValue3, 0, 1023, 140, -140);

  averageValue1 = 0;
  averageValue2 = 0;
  for (int loop = averageCount; loop > 0 ; loop--) {
    lastFiveValues1[loop] = lastFiveValues1[loop - 1];
    averageValue1 += lastFiveValues1[averageCount - loop];
  }
  for (int loop = averageCount; loop > 0 ; loop--) {
    lastFiveValues2[loop] = lastFiveValues2[loop - 1];
    averageValue2 += lastFiveValues2[averageCount - loop];
  }
  lastFiveValues1[0] = outputValue1;
  lastFiveValues2[0] = outputValue2;

  averageValue1 = averageValue1 / averageCount;
  averageValue2 = averageValue2 / averageCount;

  /*  // change the analog out value:
    analogWrite(analogOutPin, outputValue1);
    analogWrite(analogOutPin, outputValue2);
    analogWrite(analogOutPin, outputValue3);*/

  // print the results to the serial monitor:
  String outputString = (String)averageValue1 + " " + averageValue2;
  Serial.println(outputString);

  // wait 2 milliseconds before the next loop
  // for the analog-to-digital converter to settle
  // after the last reading:
  delay(50);
}

Это две версии for-l oop:

1 (дает правильный результат)

  averageValue1 = 0;
  averageValue2 = 0;
  for (int loop = averageCount; loop > 0 ; loop--) {
    lastFiveValues1[loop] = lastFiveValues1[loop - 1];
    averageValue1 += lastFiveValues1[averageCount - loop];
    lastFiveValues2[loop] = lastFiveValues2[loop - 1];
    averageValue2 += lastFiveValues2[averageCount - loop];
  }

  lastFiveValues1[0] = outputValue1;
  lastFiveValues2[0] = outputValue2;

  averageValue1 = averageValue1 / averageCount;
  averageValue2 = averageValue2 / averageCount;

2 (дает неправильный результат)

  averageValue1 = 0;
  averageValue2 = 0;
  for (int loop = averageCount; loop > 0 ; loop--) {
    lastFiveValues1[loop] = lastFiveValues1[loop - 1];
    averageValue1 += lastFiveValues1[averageCount - loop];
    lastFiveValues2[loop] = lastFiveValues2[loop - 1];
    averageValue2 += lastFiveValues2[averageCount - loop];
  }

  lastFiveValues1[0] = outputValue1;
  lastFiveValues2[0] = outputValue2;

  averageValue1 = averageValue1 / averageCount;
  averageValue2 = averageValue2 / averageCount;

Мне кажется, что эти две версии for-l oop должен дать тот же результат, но они этого не делают. Как это может быть?

Спасибо, ребята

...