0

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?

#include<Servo.h>
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() {
    Serial.begin(9600);
    pinMode(tpin, OUTPUT);
    pinMode(epin, INPUT);
    pinMode(red1, OUTPUT);
    pinMode(green1, OUTPUT);
    servo1.attach(Motor);

}

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

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

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

if(count>=5)
{
  //turn on green led (color may be wrong)
}
else
{
  //turn on red led (color may be wrong)
}

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.