Need Help In Leds

Hi. I am creating a traffic light with a speed checker. What i want to know is that my arduino led traffic light works fine but it gives a delay to the speed checker ( ultrasonic distance sensor ). How to Reamove that delay and still create a traffic light

Code as below :-

const int trigPin = 5;
const int echoPin = 6;
const int greenled = 2;
const int yellowled = 4;
const int redled = 3;

long duration;
int FirstDistance = 0;
int SecondDistance = 0;
double speed = 0;
int distance = 1;
float Time = 2.0;
float delayedtime = 100;

void setup()
{
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(redled,OUTPUT);
  pinMode(greenled,OUTPUT);
  pinMode(yellowled,OUTPUT);
  Serial.begin(9600);
}


void loop()
{
  GetSpeed();
  Traffic();
}

float GetDistance()
{
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  //calculating distance
  distance = duration * 0.034 / 2;

  // Prints the distance on the Serial Monitor
  Serial.print("Distance in cm : ");
  Serial.println(distance);

  return distance;

}
void GetSpeed() {

  FirstDistance = GetDistance(); //get the first distance

  delay(delayedtime); //waits 2 seconds depending on the time declared above ,, feel free to change the value dependng on the resolution of your sensor

  SecondDistance = GetDistance(); //gets the second distance

  speed = (FirstDistance - SecondDistance) / Time; // now calculating the difference


  //printing the speed on the serial monitor
  Serial.print("the speed (cm/s) is  :  ");
  Serial.println(speed);

  delay (200);

}

void Traffic() {
  digitalWrite(redled,LOW);
  digitalWrite(greenled,HIGH);
  delay(500); // 10000
  digitalWrite(yellowled,HIGH);
  digitalWrite(greenled,LOW);
  delay(500);
  digitalWrite(yellowled,LOW);
  digitalWrite(redled,HIGH);
  delay(500);  
}

Don't use delay() but a millis() based approach.

You will also need to read up on a finite state machine. In your Traffic() function you have three states; you have to keep track in which state you are and switch to the next state when it is time.

Lastly there is a non-blocking ping library (search for NewPing) that might help to get rid of delays due to your GetDistance() function.

Pls can you share the code @sterretje as i couldnt understand it. what is millis() ?

Here is the tutorial.

And here another one: Using millis() for timing. A beginners guide

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.