/ NeoPixel_Blinkendisc / NeoPixel_Blinkendisc.ino
NeoPixel_Blinkendisc.ino
 1  // SPDX-FileCopyrightText: 2017 Phillip Burgess for Adafruit Industries
 2  //
 3  // SPDX-License-Identifier: MIT
 4  
 5  #include <Adafruit_NeoPixel.h>
 6  
 7  #define NUM_LEDS              24 // 24 LED NeoPixel ring
 8  #define NEOPIXEL_PIN           0 // Pin D0 on Gemma
 9  #define VIBRATION_PIN          1 // Pin D1 on Gemma
10  #define ANALOG_RANDOMNESS_PIN A1 // Not connected to anything
11  
12  #define DEFAULT_FRAME_LEN     60
13  #define MAX_FRAME_LEN        255
14  #define MIN_FRAME_LEN          5
15  #define COOLDOWN_AT         2000
16  #define DIM_AT              2500
17  #define BRIGHTNESS_HIGH      128
18  #define BRIGHTNESS_LOW        32
19  
20  Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUM_LEDS, NEOPIXEL_PIN);
21  
22  uint32_t color          = pixels.Color(0, 120, 30);
23  uint8_t  offset         = 0;
24  uint8_t  frame_len      = DEFAULT_FRAME_LEN;
25  uint32_t last_vibration = 0;
26  uint32_t last_frame     = 0;
27  
28  void setup() {
29    // Random number generator is seeded from an unused 'floating'
30    // analog input - this helps ensure the random color choices
31    // aren't always the same order.
32    randomSeed(analogRead(ANALOG_RANDOMNESS_PIN));
33    // Enable pullup on vibration switch pin.  When the switch
34    // is activated, it's pulled to ground (LOW).
35    pinMode(VIBRATION_PIN, INPUT_PULLUP);
36    pixels.begin();
37  }
38  
39  void loop() {
40    uint32_t t;
41  
42    // Compare millis() against lastFrame time to keep frame-to-frame
43    // animation timing consistent.  Use this idle time to check the
44    // vibration switch for activity.
45    while(((t = millis()) - last_frame) <= frame_len) {
46      if(!digitalRead(VIBRATION_PIN)) { // Vibration sensor activated?
47        color = pixels.Color(           // Pick a random RGB color
48          random(256), // red
49          random(256), // green
50          random(256)  // blue
51        );
52        frame_len = DEFAULT_FRAME_LEN; // Reset frame timing to default
53        last_vibration = t;            // Save last vibration time
54      }
55    }
56  
57    // Stretch out frames if nothing has happened in a couple of seconds:
58    if((t - last_vibration) > COOLDOWN_AT) {
59      if(++frame_len > MAX_FRAME_LEN) frame_len = MIN_FRAME_LEN;
60    }
61  
62    // If we haven't registered a vibration in DIM_AT ms, go dim:
63    if((t - last_vibration) > DIM_AT) {
64      pixels.setBrightness(BRIGHTNESS_LOW);
65    } else {
66      pixels.setBrightness(BRIGHTNESS_HIGH);
67    }
68  
69    // Erase previous pixels and light new ones:
70    pixels.clear();
71    for(int i=0; i<NUM_LEDS; i += 6) {
72      pixels.setPixelColor((offset + i) % NUM_LEDS, color);
73    }
74  
75    pixels.show();
76  
77    // Increase pixel offset until it hits 6, then roll back to 0:
78    if(++offset == 6) offset = 0;
79  
80    last_frame = t;
81  }