Serial Read Prog Not Working

Hi,

Not sure if anyone can help me I am trying to make some simple code (Else If statement) to turn 2xLED’s on/off but the code below doesn’t seem to turn any of the LED’s off no matter what serial letter is sent? Any help would be appreciated!

Code :-

char e = Serial.read();
}
      
if(e == 'f')
{    
pinMode(8, OUTPUT);            
digitalWrite(8, LOW);        
delay(96);                         
pinMode(9, OUTPUT);              
digitalWrite(9, LOW);             
delay(96);                         
}    
else if(e == 'w')
{
pinMode(8, OUTPUT);            
digitalWrite(8, HIGH);            
delay(96);                         
pinMode(9, OUTPUT);               
digitalWrite(9, LOW);            
delay(96); 
digitalWrite(LED_BUILTIN, HIGH);
delay(96);  
digitalWrite(LED_BUILTIN, LOW);  
delay(96);
}
else if(e == 'h')
{
pinMode(8, OUTPUT);               
digitalWrite(8, HIGH);            
delay(96);                         
pinMode(9, OUTPUT);               
digitalWrite(9, HIGH);           
delay(96);                         
digitalWrite(8, LOW);             
digitalWrite(9, LOW);            
}

This is not a complete sketch. please post the complete sketch.

Hard to say without seeing all your code, but I’ll guess that you should remove the char from this:

char e = Serial.read();

Please post the entire code. There is a closing bracket after the char e definition. That code should not even compile. Google variable scope.

My apologies guys!
I think perhaps it may be some brackets in the wrong place, or even that I need to make a named subroutine for the LED blinking and declare it later in the code?
The LED blinking works off 1 character that can be either ‘h’, ‘w’ or ‘f’ and is supposed to blink 2 output LED’s but doesn’t!
Here is the full code it’s basically for serial communications between two arduino’s and this is the receiver code:-

const int ledPin = LED_BUILTIN; // pin the LED is connected to
char a;
char b;
char c;
char d;
char e;

void setup()
{
Serial.begin(9600); // Initialize serial port to send and receive at 9600 baud
pinMode(LED_BUILTIN, OUTPUT);

}

void loop()
{
void start(void);
if ( Serial.available()) // Check to see if at least one character is available

char a = Serial.read();            // Start Sequence 1/3
char b = Serial.read();            // Start Sequence 2/3
char c = Serial.read();            // Start Sequence 3/3

if(a == '@' & b == '~' & c == 'u') // Has start sequence been received?

char e = Serial.read();
digitalWrite(LED_BUILTIN, HIGH);
delay(96); 
digitalWrite(LED_BUILTIN, LOW);
delay(96);

       
if(e == 'f')
{    
pinMode(8, OUTPUT);               
digitalWrite(8, LOW);             
delay(96);                      
pinMode(9, OUTPUT);              
digitalWrite(9, LOW);             
delay(96);                         
}    
else if(e == 'w')
{
pinMode(8, OUTPUT);               
digitalWrite(8, HIGH);            
delay(96);                        
pinMode(9, OUTPUT);             
digitalWrite(9, LOW);            
delay(96); 
}
else if(e == 'h')
{
pinMode(8, OUTPUT);               
digitalWrite(8, HIGH);           
delay(96);                         
pinMode(9, OUTPUT);               
digitalWrite(9, HIGH);          
delay(96);                         
digitalWrite(8, LOW);             
digitalWrite(9, LOW);             
}    

                   
else

{
return(0);
}
return(0);
}

if 1 byte is available, read 3 bytes. Does that sound like it should work right? Check out the serial input basics tutorial.

You declare some char variables (a-e) outside of loop() then declare the same ones again in loop(). Why?

Take a look at my Arduino Software Solutions tutorial’s first example for reading one char cmds from Serial (non-blocking)

This still does not compile.

void loop()
{
void start(void);

you can not define a function within another one.
Groundfungus’s point is valid, if you are going to read a byte, you need to make sure it is available.
By re-declaring the variable (a, b, c etc.) you make the global variable with the same name unavailable. I don’t think there is something that will change when you don’t do that, actually the global variables are never used, but it is rarely what one wants to do.
‘e’ is the variable that is actually used for comparing.

const int ledPin = LED_BUILTIN; // pin the LED is connected to

no need for that either so far, you never use ‘ledPin’

anyway if you are going to read 4 bytes, you should wait to makes sure these are there

if ( Serial.available() >= 4)  {  // and don't forget about the opening brace for the condition execution
if(a == '@' & b == '~' & c == 'u') // Has start sequence been received?

what if there was 1 stray character and b==’@’ etc.

check out Robin2’s

Could you post your code using code tags by selecting the code in the IDE, right-click and select “Copy for forum” and paste it here.
hitting the </> code-tags button here on the forum is also starting to work properly,
but omitting them here makes the forum respond to the indentation in your sketch.

Hello
Describe in simple words what the function should do, and that quite simply.

You need to learn about how to use brackets to define blocks of code. Look at the following, see the comments.

if ( Serial.available()) // Check to see if at least one character is available

      char a = Serial.read();             // this will execute if 1 byte is available
   char b = Serial.read();              // this will execute unconditionally
   char c = Serial.read();              // this will execute unconditionally

   if (a == '@' & b == '~' & c == 'u') // Has start sequence been received?

      char e = Serial.read();  // this will execute if the if is true
   digitalWrite(LED_BUILTIN, HIGH);  // this will execute unconditionally
   delay(96);       // this will execute unconditionally
   digitalWrite(LED_BUILTIN, LOW);  // this will execute unconditionally
   delay(96);       // this will execute unconditionally

Why are the pinModes set for pins 8 and 9 not set in setup()? Are the pinModes going to change?

Here is example code using a modified example 2 from Robin2’s serial input basics tutorial. You enter the start sequence (@~u) and the command (f, w or h) in serial monitor. The entry would look like @~uh. The program reads all of the input into a string (null terminated character array) and pulls the individual characters out by array indexing. Then compares to the required start sequence and pulls the command character and lights or turns off the appropriate LEDs.

const int ledPin1 = LED_BUILTIN;
const int ledPin2 = 8;
const int ledPin3 = 9;

const byte numChars = 16;
char receivedChars[numChars];   // an array to store the received data

boolean newData = false;

void setup()
{
   Serial.begin(9600);
   Serial.println("<Arduino is ready>  ENTER THE SEQUENCE \"@~uh\" for example");
   pinMode(ledPin1, OUTPUT);
   pinMode(ledPin2, OUTPUT);
   pinMode(ledPin3, OUTPUT);
}

void loop()
{
   recvWithEndMarker();
   //showNewData();
   if (newData)
   {
      parseData();
   }
}

void recvWithEndMarker()
{
   static byte ndx = 0;
   char endMarker = '\n';
   char rc;

   while (Serial.available() > 0 && newData == false)
   {
      rc = Serial.read();

      if (rc != endMarker)
      {
         receivedChars[ndx] = rc;
         ndx++;
         if (ndx >= numChars)
         {
            ndx = numChars - 1;
         }
      }
      else
      {
         receivedChars[ndx] = '\0'; // terminate the string
         ndx = 0;
         newData = true;
      }
   }
}

void showNewData()
{
   if (newData == true)
   {
      Serial.print("This just in ... ");
      Serial.println(receivedChars);
      //newData = false;
   }
}

void parseData()
{
   if (receivedChars[0] == '@' && receivedChars[1] == '~' && receivedChars[2] == 'u')
   {
      Serial.println("Starting sequence accepted");
      if (receivedChars[3] == 'f')
      {
         Serial.println("received an f");
         digitalWrite(ledPin2, LOW);
         delay(96);
         digitalWrite(ledPin3, HIGH);
         delay(96);
      }
      else if (receivedChars[3] == 'w')
      {
         Serial.println("received a w");
         digitalWrite(ledPin2, HIGH);
         delay(96);
         digitalWrite(ledPin3, LOW);
         delay(96);
      }
      else if (receivedChars[3] == 'h')
      {
         Serial.println("received an h");
         digitalWrite(ledPin2, HIGH);
         delay(96);
         digitalWrite(ledPin3, HIGH);
         delay(96);
         digitalWrite(ledPin2, LOW);
         digitalWrite(ledPin3, LOW);
      }
   }
   newData = false;
}

Hi, Thanks for the input all particularly Groundfungus with the code you suggested I have tried this and now works. I send the correct key sequence via serial from the arduino console and it now lights the correct LED! This unfortunately has presented a new problem as my transmitter code which is sending the same sequence every few milliseconds serial is now not recognised? I am basically looping -
Serial.print("@~uh");
every second but get no reply off the receiver even when I send the same characters serially via the arduino code and works? Is there a particular serial.print format to use ?

Hi all, Groundfungus I apologise I have now got my transmitter code to work also :slight_smile: I basically had to add in some “Serial.println(”");" to add returns in the serial sends (breaks). I have put the full transmitter code below (a lot simpler than the original receiver code). Thanks again!

const int MOV5 = 5; // the number of the pushbutton pin
const int MOV6 = 6; // the number of the LED pin
int buttonState5 = 0; // variable for reading the pushbutton status
int buttonState6 = 0;

void setup()
{
Serial.begin(9600); // Initialize serial port to send and receive at 9600 baud
pinMode(LED_BUILTIN, OUTPUT);
// variables will change:
pinMode(MOV5, INPUT);
pinMode(MOV6, INPUT);
}

void loop()
{
delay(960);
Serial.println("");
Serial.print("@~u"); // constants won’t change. They’re used here to set pin numbers:
delay(9);
pinMode(5, INPUT);
buttonState5 = digitalRead(5);
pinMode(6, INPUT);
buttonState6 = digitalRead(6);
if ((buttonState5 == HIGH) && (buttonState6 == HIGH)) {
Serial.print(‘h’); // L1 Healthy
}
if ((buttonState5 == HIGH) && (buttonState6 == LOW)) {
Serial.print(‘w’); // L1 Warning
}
if ((buttonState5 == LOW) && (buttonState6 == HIGH)) {
Serial.print(‘w’); // L1 Warning
}
if ((buttonState5 == LOW) && (buttonState6 == LOW)) {
Serial.print(‘f’); // L1 Fail
Serial.println("");
}

else
{
return(0);
}
return(0);
}