#include <Adafruit_NeoPixel.h>
// Define pin numbers
const int forwardButton = 6;
const int direction = 2;
const int pulse = 3;
const int ledPin = 7; // Pin data Neopixel
const int numPixels = 16; // Jumlah LED pada ring
// Define timing for stepper motor
int time = 13000; // Set a pulse length of the stepper or speed of the stepper motor in microseconds
// Create Neopixel object
Adafruit_NeoPixel ring = Adafruit_NeoPixel(numPixels, ledPin, NEO_GRB + NEO_KHZ800);
void setup() {
// Set pin modes
pinMode(forwardButton, INPUT_PULLUP);
pinMode(direction, OUTPUT);
pinMode(pulse, OUTPUT);
// Initialize Neopixel
ring.begin();
ring.show(); // Initialize all pixels to 'off'
// Set initial state for stepper motor
digitalWrite(direction, LOW);
digitalWrite(pulse, LOW);
}
void loop() {
// Read the status of forward button
int forwardState = digitalRead(forwardButton);
// Check the forward button status
if (forwardState == LOW) {
delay(10); // Debounce
if (forwardState == LOW) {
digitalWrite(direction, LOW); // Set the stepper motor clockwise direction
runningLightEffect(); // Display running light effect
do {
digitalWrite(pulse, HIGH);
delayMicroseconds(time);
digitalWrite(pulse, LOW);
delayMicroseconds(time);
forwardState = digitalRead(forwardButton); // Read the forward button status again
}
while (forwardState != HIGH); // Continue until button is released
}
} else {
turnOffRing(); // Turn off Neopixel ring when button is not pressed
}
}
void runningLightEffect() {
// Rotate through the LED ring with 3 LEDs on at a time
int ledOffset = 0;
while (digitalRead(forwardButton) == LOW) { // Continue while button is pressed
ring.clear(); // Clear the ring
for (int i = 0; i < 3; i++) { // Light up 3 LEDs
int pixelIndex = (ledOffset + i) % numPixels;
ring.setPixelColor(pixelIndex, ring.Color(255, 255, 255)); // Set LED to white
}
ring.show();
// Move the stepper motor
digitalWrite(pulse, HIGH);
delayMicroseconds(time);
digitalWrite(pulse, LOW);
delayMicroseconds(time);
delay(100); // Adjust the speed of the effect
ledOffset = (ledOffset + 1) % numPixels; // Move the offset
}
}
void turnOffRing() {
for (int i = 0; i < numPixels; i++) {
ring.setPixelColor(i, ring.Color(0, 0, 0)); // Set LED to off
}
ring.show();
}