Alex Glow
Published

Modulo and If Statements: Arduino Basics

Create a device that switches modes, using these two handy operators.

IntermediateProtip2 hours5,751
Modulo and If Statements: Arduino Basics

Things used in this project

Story

Read more

Code

Ring Light code

C/C++
Adapted from Adafruit's "simple" example sketch for the NeoPixel library.
// NeoPixel Ring simple sketch (c) 2013 Shae Erisson
// released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1
#define PIN            1

// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS      24

// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
// example for more information on possible values.
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int delayval = 150; // debounce & color-wipe delay

const int button = 2;
int buttonState = 0;
int colorMode = 0;
int rVal = 255;
int bVal = 255;
int gVal = 255;

void setup() {
  pinMode(button, INPUT);
  pixels.begin(); // This initializes the NeoPixel library.
}

void loop() {

  // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.
  buttonState = digitalRead(button);
  
  if (buttonState == HIGH) {
    for(int i=0;i<NUMPIXELS;i++) {

    // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
    pixels.setPixelColor(i, pixels.Color(rVal,gVal,bVal)); // Moderately bright green color.

    pixels.show(); // This sends the updated pixel color to the hardware.

    delay(delayval); // Delay for a period of time (in milliseconds). Useful for debounce
    }
    
    colorMode = (colorMode + 1) % 4;
    
    if (colorMode == 1) {
      // warm light
      rVal = 255;
      gVal = 200;
      bVal = 100;
    } else if (colorMode == 2) {
      // dim white
      rVal = 100;
      gVal = 100;
      bVal = 100;
    } else if (colorMode == 3) {
      // dim, warm light
      rVal = 100;
      gVal = 80;
      bVal = 40;
    } else {
      // back to full brightness, all white
      rVal = 255;
      gVal = 255;
      bVal = 255;
    }
    
  } else {
    // do nuthin
  }

}

Credits

Alex Glow

Alex Glow

145 projects • 1569 followers
The Hackster team's resident Hardware Nerd. I love robots, music, EEG, wearables, and languages. FIRST Robotics kid.

Comments