I want to connect a flashing rgb led in my Bluetooth controlled Arduino car which constantly flash as red-blue-red-blue.... I have made a code and it flashes led as required but when I connect Bluetooth module(HC05), led starts working abnormally. I think its a coding problem please have a look on my code and help me out of this, as I am new in this... maybe its a bad programming
char junk;
String inputString="";
const int lf=9;// motor
const int rf=3;// motor
const int lb=10;// motor
const int rb=11;// motor
const int light=5;
const int r=8; // red led
const int b=7; // blueled
unsigned long tm=0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(lf, OUTPUT);
pinMode(rf, OUTPUT);
pinMode(lb, OUTPUT);
pinMode(rb, OUTPUT);
pinMode(light, OUTPUT);
pinMode(r, OUTPUT);
pinMode(b, OUTPUT);
digitalWrite(r,LOW);// low due to common cathode rgb led
}
void loop()
{
rgb(); // function to flash rgb led
if(Serial.available())
{
while(Serial.available())
{
char inChar = (char)Serial.read(); //read the input
inputString += inChar; //make a string of the characters coming on serial
}
Serial.println(inputString);
while (Serial.available() > 0)
{ junk = Serial.read() ; } // clear the serial buffer
if(inputString == "f")
{
forward();
}
else if(inputString == "b")
{
backward();
}
else if(inputString == "l")
{
left();
}
else if(inputString == "r")
{
right();
}
else if(inputString == "z")
{
forleft();
}
else if(inputString == "x")
{
forright();
}
else if(inputString == "v")
{
backleft();
}
else if(inputString == "c")
{
backright();
}
else if(inputString == "s")
{
stopp();
}
else if(inputString == "n")
{
digitalWrite(light,HIGH);
}
else if(inputString == "m")
{
digitalWrite(light,LOW);
}
inputString = "";
}
}
void forward()
{
digitalWrite(lf,HIGH);
digitalWrite(rf,HIGH);
}
void backward()
{
digitalWrite(lb,HIGH);
digitalWrite(rb,HIGH);
}
void left()
{
digitalWrite(rf,HIGH);
}
void right()
{
digitalWrite(lf,HIGH);
}
void forleft()
{
analogWrite(lf,150);
analogWrite(rf,255);
}
void forright()
{
analogWrite(rf,150);
analogWrite(lf,255);
}
void backleft()
{
analogWrite(lb,150);
analogWrite(rb,255);
}
void backright()
{
analogWrite(rb,150);
analogWrite(lb,255);
}
void stopp()
{
digitalWrite(lf,LOW);
digitalWrite(lb,LOW);
digitalWrite(rf,LOW);
digitalWrite(rb,LOW);
}
void rgb() // red-blue-red-blue....
{
if(millis()-tm>500)
{
if(digitalRead(r)==LOW)
{
digitalWrite(r,HIGH);
digitalWrite(b,LOW);
tm=millis();
}
else if(digitalRead(b)==LOW)
{
digitalWrite(b,HIGH);
digitalWrite(r,LOW);
tm=millis();
}
}
}
the function for flashing is in the last which is called in the starting of void loop. Also I have used digitalWrite(r,LOW); to turn on the red led because it is a common cathode led, same as for blue.