-1
\$\begingroup\$

I am building a color sorting machine using a Arduino uno and a TCS3200 color sensor. I have a code that is working perfectly fine however I feel like the code could be a bit more clean seeing that I am using 3 almost identical for loops. Could anyone help me re-write these 3 for loops into one loop. Thank you in advance!

Like I mentioned the code works perfectly fine. I only need some help re-writing these 3 for loops

void loop() {

  delay(150);
  float frequencyR[3];

for(unsigned int i = 0; i < 3; i++) {
  delay(150);
  digitalWrite(S2, LOW);
  digitalWrite(S3, LOW);
  frequencyR[i] = pulseIn(sensorOut, LOW);

  delay(150);

  }
  float frequencyG[3];

for(unsigned int i = 0; i < 3; i++) {
  delay(150);
  digitalWrite(S2, HIGH);
  digitalWrite(S3, HIGH);
  frequencyG[i] = pulseIn(sensorOut, LOW);

  delay(150);

  }
  float frequencyB[3];

for(unsigned int i = 0; i < 3; i++) {
  digitalWrite(S2, LOW);
  digitalWrite(S3, HIGH);
  frequencyB[i] = pulseIn(sensorOut, LOW);

  delay(150);

  }

\$\endgroup\$
2
  • \$\begingroup\$ Hi Nils, could you rework your indentation? I'm sure you can see now that it's not as it should be (I'm assuming this isn't the way your code is indented in your real code) \$\endgroup\$
    – IEatBagels
    Aug 22 '19 at 13:09
  • 1
    \$\begingroup\$ You're reading values into local arrays, and not doing anything with them? Please show us your real code, with context, so that we can give you proper advice. See How to Ask. \$\endgroup\$ Aug 23 '19 at 5:48
1
\$\begingroup\$

Pass the pin values as ints and the array as a float pointer.

void sample(int pin1, int pin2, float *result){
    for(unsigned int i = 0; i < 3; i++) {
      digitalWrite(S2, pin1);
      digitalWrite(S3, pin2);
      result[i] = pulseIn(sensorOut, LOW);

      delay(150);

  }
}

And you call it with:

float frequencyR[3];
sample(LOW, LOW, frequencyR);

float frequencyG[3];
sample(HIGH, HIGH, frequencyG);

float frequencyB[3];
sample(LOW, HIGH, frequencyB);
\$\endgroup\$
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.