My RGB led is not working properly. It should light up red when the ultrasonic sensor detects more than 10 cm and green when it detects less than or equal 10 cm. It is just blinking red and green at the same time. How do I fix this?

Servo servo1;
int Motor = 3;
int tpin = 7;
int epin = 6;
int red1 = 12;
int green1 = 13;
int pos = 0;
long duration, inches, cm;

void setup() {
    pinMode(tpin, OUTPUT);
    pinMode(epin, INPUT);
    pinMode(red1, OUTPUT);
    pinMode(green1, OUTPUT);


void loop() {
    digitalWrite(tpin, LOW);
    digitalWrite(tpin, HIGH);
    digitalWrite(tpin, LOW);
    duration = pulseIn(epin, HIGH);
    cm = (duration / 2) / 29.1;
    inches = (duration / 2) / 74;
    Serial.print("in, ");

    if ((cm > 10))
        servo1.write(pos = 0);
        digitalWrite(red1, HIGH);
        digitalWrite(red1, LOW);
        Serial.println("\t RED");
    else if ((cm <= 10))
        servo1.write(pos = 90);
        digitalWrite(green1, HIGH);
        digitalWrite(green1, LOW);
        Serial.println("\t GREEN");
| improve this question | | | | |
  • 1
    What output are you seeing in the console? – RamblinRose Mar 13 '19 at 15:00
  • RGB LED has nothing to do with the issue, so the title is misleading. – SBF Mar 13 '19 at 17:21
  • blinking red and green at the same time .... that means blinking yellow ..... is that correct? – jsotola Mar 13 '19 at 19:19

The ultrasonic sensor scans every 0,1 seconds according to your code. Problem is, sometimes you have "faulty" results. Taking into consideration the frequency of your scans + the "faulty" scans, it could be that your arduino just keeps switching between those two LEDs.

What helped me back then was to make a counter. A variable, that counts how many times in a row the distance to the object is "distance <10cm". If the streak was interrupted, it would reset the variable. This is how a serial output would display it:

distance: 20cm
distance: 16cm
distance: 8cm
count: 1
distance: 9cm
count: 2
distance: 6cm
count: 3
distance: 8cm
count: 4
distance: 11cm
count: 0
distance: 12cm
distance: 20cm

And the moment your counter reaches a certain spot, for example the object is closer than 10cm five times in a row, then you will let an led light up

  //turn on green led (color may be wrong)
  //turn on red led (color may be wrong)
| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.