Refactor 2

Multiple lines of code that are repeated in multiple locations are another good candidate for refactoring. For example, these lines appear in two locations.

Download: file
  for (int p=0; p<10; p++) {
    CircuitPlayground.setPixelColor(p, 0xFF6600);
  }

Functionally, they turn on all of the NeoPixels to the given color. Let's refactor that functionality out into a new function called showPixels().

Download: file
void showPixels(uint32_t color) {
  for (int p=0; p<10; p++) {
    CircuitPlayground.setPixelColor(p, color);
  }  
}

Now we can just call that function in our indicateYes() and indicateNo() functions. Here's the new code with all these new changes.

Download: file
///////////////////////////////////////////////////////////////////////////////
// Circuit Playground Yes No v2
//
// One beep (left button) = Yes
// Two beeps (right button) = No
//
// Author: Carter Nelson
// MIT License (https://opensource.org/licenses/MIT)

#include <Adafruit_CircuitPlayground.h>

///////////////////////////////////////////////////////////////////////////////
void showPixels(uint32_t color) {
  for (int p=0; p<10; p++) {
    CircuitPlayground.setPixelColor(p, color);
  }  
}
  
///////////////////////////////////////////////////////////////////////////////
void indicateYes() {
  showPixels(0xFF6600);
  CircuitPlayground.playTone(700, 750);
  CircuitPlayground.clearPixels();
}

///////////////////////////////////////////////////////////////////////////////
void indicateNo() {
  showPixels(0xFF6600);
  CircuitPlayground.playTone(700, 500);
  CircuitPlayground.clearPixels();    
  delay(250);
  showPixels(0xFF6600);
  CircuitPlayground.playTone(700, 500);
  CircuitPlayground.clearPixels();
}     

///////////////////////////////////////////////////////////////////////////////
void setup() {
  CircuitPlayground.begin();
}

///////////////////////////////////////////////////////////////////////////////
void loop() {
  if (CircuitPlayground.leftButton()) {
    indicateYes();
  }  
  if (CircuitPlayground.rightButton()) {
    indicateNo();    
  }
}

More importantly, we can now use this function anywhere else. This could be useful as the code grows and you find you want to turn on all the NeoPixels again somewhere else for some reason. Well, now there's a convenient little function you can call to do that. No need to write the loop() over and over again.

This guide was first published on Jan 23, 2017. It was last updated on Jan 23, 2017.
This page (Refactor 2) was last updated on Dec 29, 2019.