Multiple lines of code that are repeated in multiple locations are another good candidate for refactoring. For example, these lines appear in two locations.
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()
.
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.
/////////////////////////////////////////////////////////////////////////////// // 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.
Page last edited January 13, 2017
Text editor powered by tinymce.