I'm trying to light leds on and off in a loop when I receive data from BT. But when I send "r" through BT the led strip turns ON and OFF and does it in a loop but when I send "b" or "g" or "o" it doesn't change or turn off but keeps looping in first function.
I need a way to stop the " for int" and change to other function.
all functions need to be always in loop until I change it through BT.
Hope you understand.
BT= Bluetooth
#include "FastLED.h" // FastLED library.
// Fixed definitions cannot change on the fly.
#define LED_DT 7 // Data pin to connect to the strip.
#define COLOR_ORDER GRB // It's GRB for WS2812 and BGR for APA102.
#define LED_TYPE WS2812B // Using APA102, WS2812, WS2801. Don't forget to change LEDS.addLeds.
#define NUM_LEDS 23 // Number of LED's.
struct CRGB leds[NUM_LEDS]; // Initialize our LED array.
int val;
void setup() {
Serial.begin(9600); // Initialize serial port for debugging.
delay(1000); // Soft startup to ease the flow of electrons.
LEDS.addLeds<LED_TYPE, LED_DT, COLOR_ORDER>(leds, NUM_LEDS);
}
void loop () {
if (Serial.available())
{
val = Serial.read();
if (val == 'r') // red
{
red();
}
if (val == 'g') // green
{
green();
}
if (val == 'b') // blue
{
blue();
}
if (val == 'o') //off
{
FastLED.clear ();
}
}
}
void red()
{
fill_solid(leds, NUM_LEDS, CRGB::Red);
FastLED.show(); // Power managed display
FastLED.delay(1000);
FastLED.clear ();
FastLED.delay(1000);
}
void green()
{
for(int i = 0; i < 1000; i++)
{
fill_solid(leds, NUM_LEDS, CRGB::Green);
FastLED.show(); // Power managed display
FastLED.delay(1000);
FastLED.clear ();
FastLED.delay(1000);
}
}
void blue()
{
for(int i = 0; i < 1000; i++)
{
fill_solid(leds, NUM_LEDS, CRGB::Blue);
FastLED.show(); // Power managed display
FastLED.delay(1000);
FastLED.clear ();
FastLED.delay(1000);
}
}
You should use the state of your program so that it can continue to test for keypresses, while still blinking the LEDs. Also, don't forget to show()
the updated LEDs, also after a clear()
. For example
#define MAXBLINKS 1000
int blinkCount = 0;
int lastKey = 0;
void loop () {
if (Serial.available()) {
// lastKey is kept because it is global
// and not overwritten until a new key is pressed
lastKey = Serial.read();
}
if (lastKey != 0) {
switch (lastKey) {
case 'r':
blink(CRGB::Red);
break;
case 'g':
blink(CRGB:Green);
break;
case 'b':
blink(CRGB::Blue);
break;
}
blinkCount++;
// Stop blinking after MAXBLINKS,
// or immediately for certain keys
if (blinkCount > MAXBLINKS || lastKey == 'r') {
blinkCount = 0;
lastKey = 0;
}
}
}
// blink will take TWO seconds before it returns
// -- not sure CRGB is the right type
void blink(CRGB clr)
{
fill_solid(leds, NUM_LEDS, clr);
FastLED.show();
FastLED.delay(1000);
FastLED.clear();
FastLED.show();
FastLED.delay(1000);
}
Because blink()
here takes two seconds, this is how long you may have to wait before a keypress takes effect.