Hi everybody,
I'm new to writing code for the Arduino and I'm having some trouble. I have set up two LEDs (one blue, one yellow) and I'm using them to simulate a motor. The yellow LED indicates direction. On for forwards and off for backwards. The blue LED I want to pulse as an indication of speed.
I want to be able to control it all over the serial port. This is what I have so far:
int MotorDir = 12;
int MotorSpd = 11;
int incomingByte = 0;
int Spd = 0;
void flash(int S)
{
Serial.println(S, BYTE);
digitalWrite(MotorSpd, HIGH);
delay(1000 - S*100);
digitalWrite(MotorSpd, LOW);
delay(1000 - S*100);
}
void setup()
{
pinMode(MotorDir, OUTPUT);
pinMode(MotorSpd, OUTPUT);
Serial.begin(9600); // set up Serial library at 9600 bps
}
void loop()
{
if (Serial.available() > 0)
{
incomingByte = Serial.read();
Serial.print("I received: ");
Serial.println(incomingByte, BYTE);
if (incomingByte == 'Y') {
incomingByte = Serial.read();
if (incomingByte == '1') {
digitalWrite(MotorDir, HIGH);
}
if (incomingByte == '0') {
digitalWrite(MotorDir, LOW);
}
}
if (incomingByte == 'B') {
Spd = Serial.read();
Serial.println(Spd, BYTE);
}
}
flash(Spd);
}
Turning the yellow LED on and off works fine. I.e. if I type Y1 into the serial monitor it turns on and if I type Y0 it turns off.
When the program starts, the blue LED flashes at the required speed but if I type B2 (for example) into the serial monitor the blue LED turns on, stays on and the Arduino wont accept any more commands. I think it may be getting stuck in the "flash" function but I'm not sure how or why.
Can anybody help or offer a suggestion?
Thanks