I am trying to write some code to make 3 LED's flicker and the can be turned on and off with bluetooth.
The code below will begin the do while loop when I send a. It continues because their is no break. If I put in a break it sets the three LEDs to a single random voltage.
How can I start and stop a loop like that with a serial input? What is am doing wrong? The code is below.
char data = 0;
int ledPin1 = 9;
int ledPin2 = 10;
int ledPin3 = 11;
//Variable for storing received data
void setup()
{
Serial.begin(9600); //Sets the data rate in bits per second (baud) for serial data transmission
}
void loop()
{
if(Serial.available() > 0) // Send data only when you receive data:
{
data = Serial.read(); //Read the incoming data and store it into variable data
Serial.print(data);
}
else{}
switch (data)
{
case 'a':
do
{
analogWrite(ledPin1, random(120)+135);
analogWrite(ledPin2, random(120)+135);
analogWrite(ledPin3, random(120)+135);
delay(random(100));
Serial.print(data);
}
while (data == 'a');
case 'w':
analogWrite(ledPin1, 0);
analogWrite(ledPin2, 0);
analogWrite(ledPin3, 0);
delay(random(100));
break;
}
}
What do you have in your Serial monitor settings for "line ending"?
Your current solution requires a 1-character line-ending. It will have a glitch when you enter the next command because it will read the line-ending character that was sitting in the buffer and act on its value before reading the actual command following.
You should always inspect the value of the incoming character before you store it in the permanent "data" variable. If it's not something you expect then just ignore it.