Skip to content

Incorrect Serial data handling in RGB LED control code (Serial.parseInt issue) #2456

@Mojirade18

Description

@Mojirade18

🐛 Description

The current Arduino sketch for RGB LED control does not reliably read serial input.
It uses both Serial.read() and Serial.parseInt() in the same loop, which can cause timing and parsing issues.
As a result, the LED sometimes fails to respond correctly to commands like R255 or G128.


⚙️ Steps to Reproduce

  1. Upload the existing code to Arduino.
  2. Open Serial Monitor.
  3. Send commands such as R255, G128, or B60.
  4. Observe that the LED does not always update as expected.

💡 Expected Behavior

Each command (R, G, or B followed by a value) should set the corresponding LED brightness immediately and consistently.


🧠 Possible Solution

Use a safer approach:

  • Wait until all serial data is available.
  • Read the character and integer together.
  • Validate the input range before writing to the pins.

Example fix:

if (Serial.available()) {
  char c = Serial.read();
  while (!Serial.available());
  int value = Serial.parseInt();
  value = constrain(value, 0, 255);
  if (c == 'R') analogWrite(9, value);
  else if (c == 'G') analogWrite(10, value);
  else if (c == 'B') analogWrite(11, value);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions