Arduino Car Simulation

I am programming a traffic light simulation using Arduino and I am having some difficulty programming the car. It just needs to be able to react to to the traffic lights and shut the car off when the lights change and I am not sure how to do that. I am using two arduino UNO boards, one for the car and the other for the traffic. I am a novice programmer. There is a link for the code for the traffic it needs to react to in the post.

https://create.arduino.cc/projecthub/alikarkuki/traffic-light-4-way-7953c4

TaborTheCreator:
It just needs to be able to react to to the traffic lights and shut the car off when the lights change

Just to clarify, when you say "react to to the traffic lights" do you mean by watching them like a human driver would with some kind of colour sensor, or will the car's Arduino be connected to the lights' Arduino and be receiving a signal by some wires / wireless?

And by "car" you mean some kind of small, wheeled / tracked device that moves around the floor? (Asking because your topic header uses the phrase "car simulation", not sure what that means in this context.

TaborTheCreator:
It just needs to

I had a quiet chuckle at the "just" there.

Here for others' ease of access is OP's code:

int r1 = 1;
int y1 = 2;
int g1 = 3;
int r2 = 4;
int y2 = 5;
int g2 = 6;
int r3 = 7;
int y3 = 8;
int g3 = 9;
int r4 = 10;
int y4 = 11;
int g4 = 12;
//Eng; ALI MEKAAL
void setup() {
pinMode (r1, OUTPUT);
pinMode (y1, OUTPUT);
pinMode (g1, OUTPUT);

pinMode (r2, OUTPUT);
pinMode (y2, OUTPUT);
pinMode (g2, OUTPUT);

pinMode (r3, OUTPUT);
pinMode (y3, OUTPUT);
pinMode (g3, OUTPUT);

pinMode (r4, OUTPUT);
pinMode (y4, OUTPUT);
pinMode (g4, OUTPUT);

//ALI KARKUKI

}

void loop() { 
    
digitalWrite(g1, HIGH);
digitalWrite(r2, HIGH);
digitalWrite(r3, HIGH);
digitalWrite(r4, HIGH);
delay(9000);
digitalWrite(g1, LOW);
digitalWrite(r2, LOW);

digitalWrite(y1, HIGH);
digitalWrite(y2, HIGH);
delay(3000);
digitalWrite(y1, LOW);
digitalWrite(y2, LOW);

digitalWrite(r1, HIGH);
digitalWrite(g2, HIGH);
delay(9000);

digitalWrite(g2, LOW);
digitalWrite(r3, LOW);


digitalWrite(y2, HIGH);
digitalWrite(y3, HIGH);
delay(3000);

digitalWrite(y2, LOW);
digitalWrite(y3, LOW);


digitalWrite(r2, HIGH);
digitalWrite(g3, HIGH);
digitalWrite(r4, HIGH);
delay(9000);

digitalWrite(g3, LOW);
digitalWrite(r4, LOW);
//??? ??????? 

digitalWrite(y3, HIGH);
digitalWrite(y4, HIGH);
delay(3000);

digitalWrite(y3, LOW);
digitalWrite(y4, LOW);

digitalWrite(r3, HIGH);
digitalWrite(g4, HIGH);
delay(9000);

digitalWrite(r3, LOW);
digitalWrite(g4, LOW);
digitalWrite(r1, LOW);
digitalWrite(y1, HIGH);
digitalWrite(y4, HIGH);
delay(3000);

digitalWrite(y1, LOW);
digitalWrite(y4, LOW);


}

Are you in charge of traffic lights in Renton? That seems to be how the stupid lights here work.

Other places have more intelligent traffic lights that react to the presence, or absence, of traffic.

And, I pity the poor pedestrians in you (model) world.

How are you going to make your car aware of the traffic light? Of it's position, and heading, relative to the traffic light?

ardy_guy:
Just to clarify, when you say "react to to the traffic lights" do you mean by watching them like a human driver would with some kind of colour sensor, or will the car's Arduino be connected to the lights' Arduino and be receiving a signal by some wires / wireless?

And by "car" you mean some kind of small, wheeled / tracked device that moves around the floor? (Asking because your topic header uses the phrase "car simulation", not sure what that means in this context.

I had a quiet chuckle at the "just" there.

By react to traffic lights I mean having the car recognize the lights as a human would. It is supposed to function as a self-driving car. The function itself is pretty rudimentary as the car only needs to be able to recognize the transition stage of the traffic lights between green and red and turn off. That's it! I am a novice when it comes to programming so I am working on this project for class and plan to expound on it as my knowledge increases. I am just lost on how to program the car. They will be controlled independently through two different arduinos and respond to eachother through serial communication.

PaulS:
Are you in charge of traffic lights in Renton? That seems to be how the stupid lights here work.

Other places have more intelligent traffic lights that react to the presence, or absence, of traffic.

And, I pity the poor pedestrians in you (model) world.

How are you going to make your car aware of the traffic light? Of it's position, and heading, relative to the traffic light?

That is the problem I stumbled upon when initiating this project. I was unsure how to code the car and how to make it recognize the traffic lights. The program is supposed to be rudimentary in this stage as I am not an experienced programmer. As said by my teacher, the car only needs to be able to react to the traffic light going from yellow to red and shut off. Obviously there are more sophisticated designs for traffic lights but I am not qualified to create those types of programs at this time. Any help would be greatly appreciated.

TaborTheCreator:
By react to traffic lights I mean having the car recognize the lights as a human would. ......

I'm still unclear: "recognize as a human would" seems like a vision thing to me. Programming's the easy part once you find a sensor to reliably tell the difference between red and green, at the distances you anticipate and against any background clutter; do you have such a sensor? You talk of programming the car: so you have a car designed / built? The actual programming to move and stop, while probably simple enough (once you have the sensor to tell red from green) will depend on the hardware you have for driving the motor/s.

TaborTheCreator:
..... They will be controlled independently through two different arduinos and respond to each other through serial communication.

But then if "recognize as a human would" is via a red/green led sensor, why do the Arduinos need serial comms? What's that for?

ardy_guy:
I'm still unclear: "recognize as a human would" seems like a vision thing to me. Programming's the easy part once you find a sensor to reliably tell the difference between red and green, at the distances you anticipate and against any background clutter; do you have such a sensor? You talk of programming the car: so you have a car designed / built? The actual programming to move and stop, while probably simple enough (once you have the sensor to tell red from green) will depend on the hardware you have for driving the motor/s.

But then if "recognize as a human would" is via a red/green led sensor, why do the Arduinos need serial comms? What's that for?

Sorry for all the confusion. I see what you are saying now. "As a human would" is very inaccurate and confusing terminology in this case. All the car ( which will be setup using another arduino board) needs to be able to do is recognize when the traffic lights is transitioning from yellow to green through software and turn off. That is it! I am just puzzled how I would be able to program the car. Would I use if statements and delay changes to show that the car is and is not in motion. That is where my confusion lies

TaborTheCreator:
be able to do is recognize when the traffic lights is transitioning from yellow to green through software and turn off.

You are still not making it clear (not to me anyway, but it is 5am and I only had one coffee so far) if that recognition is via some kind of colour sensor on the car that "looks" at the leds and determines the colour, or if that recognition is via a signal in your inter-Arduino comms.

ardy_guy:
You are still not making it clear (not to me anyway, but it is 5am and I only had one coffee so far) if that recognition is via some kind of colour sensor on the car that "looks" at the leds and determines the colour, or if that recognition is via a signal in your inter-Arduino comms.

I appreciate your help! The recognition is through the inter-Arduino comms through Software serial. This should allow the car to notice when the light is yellow and stop.

Delta_G:
And you should be. You are nowhere near ready to write code. You need to decide at least how you will sense the light. Until you have figured that out it is no use even trying to think about code. How you write the code will depend entirely on how you decide to sense the light.

BTW: Sensing that light is NOT a trivial task. That is a pretty big ask of an Arduino. It's not a simple project.

But the first step has nothing to do with code. Figure out how you will sense the light and its color. Once you do that then you can get the sensors and study them and once you do that then you can start thinking about code.

Delta_G:
And you should be. You are nowhere near ready to write code. You need to decide at least how you will sense the light. Until you have figured that out it is no use even trying to think about code. How you write the code will depend entirely on how you decide to sense the light.

BTW: Sensing that light is NOT a trivial task. That is a pretty big ask of an Arduino. It's not a simple project.

But the first step has nothing to do with code. Figure out how you will sense the light and its color. Once you do that then you can get the sensors and study them and once you do that then you can start thinking about code.

The light should be sensed through software such as software serial( https://www.arduino.cc/en/Reference/SoftwareSerial ) and use that as indication of when the car should stop. This way I would not have to use a light sensor and the two boards could communicate to stop the car when the light is read.The plan was to have two arduino boards, one for the car and the other for the traffic light simulation. I already have finished the traffic but I do not know how to program the car board to show that it is in motion and communicate with the other board to show that the car has stopped. I can just use a LED to show when the car is in motion or not.

If for demo purposes you don't need the car to ever be too far from the intersection, you could just use one Arduino and a flexible wire to the car.

But that won't look at all realistic, and nor is it, since real cars are not tethered to traffic lights. Your car isn't going to be doing any sensing at all; it will essentially be getting the same signal as is controlling the LEDs in the first place. So if you use one or two Arduinos it's no more realistic.

Might as well save one, and when your code changes the LED, it can turn the car's motor off or on.

To be frank, as simulations go it's pretty weak. It might look as if the car is reacting to the LED, but in fact it's being commanded by the LED's controller.

Or.... how about wireless?

Have a look here at Robin2's tutorial on the nRF24L01 modules.

Maybe you'll get some ideas there?

(Full disclosure: I've never used those modules.)

I am working on a project where you have a traffic light and a self-driving car. The point of the project is to get two arduinos to communicate with each other via software serial in order to have the car do the first part of the self-driving process, to turn off/stop when the light changes color. To make it simple only a one-way intersection is being used. I have some code but I'm not sure I am going in the right direction as I am new to programming. All the project needs to be able to do is connect the two arduinos so that the car turns off when the traffic light is red. Any help with the coding aspect would be greatly appreciated. I will attach my code to the post.

Two_Way_Traffic_Walk_Sign_Final_Project.ino (4.32 KB)

Final_Project_Car.ino (2.13 KB)

Not if your traffic light never talks on software serial.

You also don't have a need at the traffic light for interrupts. Use a millis() based approach to change the colours of the traffic light instead of a delay based approach. Further read up on finite state machine.

Post your code.

Delta_G:
Cross post reported to mods
Arduino Car Simulation - Project Guidance - Arduino Forum

Why did you start a new thread on this? Haven't we already been helping you with this project?

I made a little progress so I didnt know if I should post more on here or make a new thread to get some additional feedback and I lost track of the post because I dont know where the notification are. It also had better clarification. I have posted the code I have now for additional support. Thanks!

Final_Project_Car.ino (2.13 KB)

Two_Way_Traffic_Walk_Sign_Final_Project.ino (4.32 KB)

Continue here.

Posts have a 9000 charater limit. Either of your codes is below that so please insert in the post instead of attaching; you can post each in separte posts once they together go over 9000 characters.

That way we can more easily copy and you don't miss out on knowledge of people that use a cell hone.

Type
** **[code]** **

Your traffic light code here
Type
** **[/code]** **
after that.

Type
** **[code]** **

Your car code here
Type
** **[/code]** **
after that.

Traffic light

/* 2017 Falcom Digital Imaging L.L.C. for
    Dean Institute of Technology PLC Class Use

    Setup Variables for Walk Cycle Components.
  You use "const int" if you want to reference a value by name -
  you use it just like any ordinary int, but you cannot change the value.
  This does not use any RAM.*/
int WalkRequest = 0;  // Variable used to store the state of the Walk Push Button
const int WalkButton = 2;
const int RedPedLED = 6;
const int WhitePedLED = 7;

//  Setup Variables for Station 1 Traffic Light Components
const int Red1LED = 8;
const int Yellow1LED = 9;
const int Green1LED = 10;

//  Setup Variables for Station 2 Traffic Light Components
const int Red2LED = 11;
const int Yellow2LED = 12;
const int Green2LED = 13;

// variables that will change:
volatile int buttonState = 0;  // variable for monitoring the pushbutton status.
/* A variable should be declared volatile whenever its value can be changed
  by something beyond the control of the code section in which it appears,
  such as a concurrently executing thread.
  In the Arduino, the only place that this is likely to occur is in sections
  of code associated with interrupts, called an interrupt service routine (ISR)  */




void setup() {
  pinMode(RedPedLED, OUTPUT);  //  Sets all LED's as OUTPUT
  pinMode(WhitePedLED, OUTPUT);
  pinMode(Red1LED, OUTPUT);
  pinMode(Yellow1LED, OUTPUT);
  pinMode(Green1LED, OUTPUT);
  pinMode(Red2LED, OUTPUT);
  pinMode(Yellow2LED, OUTPUT);
  pinMode(Green2LED, OUTPUT);
  pinMode(WalkButton, INPUT);  //  Sets Push Button as INPUT

  attachInterrupt(0, pin_ISR, CHANGE);  //  "Watches" in the background for a button press
  /* Attach an interrupt to the ISR vector to monitor Push Button.
    Number 0 (for digital pin 2) or number 1 (for digital pin 3) are used.
    Interrupts are useful for making things happen automatically in
    microcontroller programs,and can help solve timing problems.
    Good tasks for using an interrupt may include reading
    a rotary encoder, or monitoring user input */

  // Set Initial state of all red LED to HIGH
  digitalWrite (Red1LED, HIGH);
  digitalWrite (Red2LED, HIGH);
  digitalWrite (RedPedLED, HIGH);
}




void loop() {
  // put your main code here, to run repeatedly:

  // Station 1 Timing
  delay(2500);  //  2.5 Seconds of Red
  digitalWrite(Red1LED, LOW);  //  Sets Red1 OFF Green ON
  digitalWrite(Green1LED, HIGH);
  delay(15000);  // 15 Seconds of Green
  digitalWrite(Green1LED, LOW);  //  Sets Green1 OFF Yellow ON
  digitalWrite(Yellow1LED, HIGH);
  delay(3500);  // 3.5 Seconds of Yellow
  digitalWrite(Yellow1LED, LOW);  //  Sets Yellow1 OFF Red ON
  digitalWrite(Red1LED, HIGH);

  if (WalkRequest == 1) {  //  If the button has been pressed
    WalkCycle();  //  Exit main loop and run WalkCycle () function
  }



  // Station 2 Timing
  delay(2500);  //  2.5 Seconds of Red
  digitalWrite(Red2LED, LOW); digitalWrite(Green2LED, HIGH);  //  Sets Red2 OFF Green ON
  delay(15000);  // 15 Seconds of Green
  digitalWrite(Green2LED, LOW); digitalWrite(Yellow2LED, HIGH);  //  Sets Green2 OFF Yellow ON
  delay(3500);  // 3.5 Seconds of Yellow
  digitalWrite(Yellow2LED, LOW); digitalWrite(Red2LED, HIGH);  //  Sets Yellow2 OFF Red ON

  if (WalkRequest == 1) {  //  If the button has been pressed
    WalkCycle();  //  Exit main loop and run WalkCycle () function
  }
}



void WalkCycle() {
  delay(3500);  //  3.5 Second delay before "WALK" begins
  digitalWrite (WhitePedLED, HIGH); digitalWrite (RedPedLED, LOW);  // Turn on White Pedestrian Light
  delay (15000);  // 15 Second delay to allow crossing street
  digitalWrite (WhitePedLED, LOW); digitalWrite(WalkButton, LOW);  // Turn off White Pedestrian Light
  delay(250);
  for (int x = 0; x < 5; x++) {  // Flash White Ped LED 5X
    digitalWrite(WhitePedLED, HIGH);
    delay(250);
    digitalWrite(WhitePedLED, LOW);
    delay(250);
  }
  digitalWrite(RedPedLED, HIGH);
  WalkRequest = 0; //  Reset Push Button
  asm volatile ("  jmp 0");  // Soft-reset of sketch. Makes sure Station 1 "MAIN" always gets Green after a walk cycle
}




void pin_ISR() {
  buttonState = digitalRead(WalkButton);
  (WalkRequest = 1);  //  Walk button has been pressed
  // digitalWrite(WhitePedLED, buttonState);  // Test Light for Interrupt use only during testing!
}

Car

// Motion Notifications LEDS
#define CAR_ACTIVE_LED 2
#define CAR_INACTIVE_LED 3

//Motion IN/NotIN Progress
#define IDLE_STATE 0
#define DRIVING_STATE 1

#define INIT 0  //Gas is pushed
#define RUN 1 //Car is in motion
#define EXIT 2 //Gas is released, brake is pushed, and car is stopped
#define EMERGENCY_BRAKE_BUTTON 4
unsigned long driving_time = 0; // stores the target time value
unsigned long start_time = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(CAR_ACTIVE_LED, OUTPUT);
  pinMode(CAR_INACTIVE_LED, OUTPUT);
  pinMode(EMERGENCY_BRAKE_BUTTON, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(EMERGENCY_BRAKE_BUTTON), do_emergency, FALLING);
}

void loop() {
  // put your main code here, to run repeatedly:
  switch (StateVariable); {
  case IDLE_STATE:
    switch (PhaseVariable) {
      case INIT:
        digitalWrite(CAR_ACTIVE_LED, LOW);
        digitalWrite(CAR_INACTIVE_LED, HIGH);
        PhaseVariable = RUN;
        break;
      case RUN:
        if (digitalRead(CAR_INACTIVE_LED) == LOW) {
          PhaseVariable = EXIT;
        }
        break;
      case EXIT:
        StateVariable = DRIVING_STATE;
        PhaseVariable = INIT;
        break;
    }
    break;
  case DRIVING_STATE:
    switch (PhaseVariable) {
      case INIT:
        digitalWrite(CAR_ACTIVE_LED, LOW);
        digitalWrite(Car_INACTIVE_LED, HIGH);
        PhaseVariable = RUN;
        start_time = millis();
        break;
      case RUN:
        if (!digitalRead(EMERGENCY_BRAKE_BUTTON)) {
          PhaseVariable = EXIT;
          break;

          )
          if (digitalRead(EMERGENCY_BRAKE_BUTTON) == LOW) {
            PhaseVariable = EXIT;
            break;
          }
          break;
        case EXIT:
            digitalWrite(CAR_ACTIVE_LED, LOW);
            digitalWrite(CAR_INACTIVE_LED, HIGH);
            StateVariable = IDLE_STATE;
            PhaseVariable = INIT;
            break;
          }
        break;
    }




  }

Your missing a } at the end of the car code :wink:

Thanks Im new to this forum so I have little experience on how to navigate it. Would you know how to incorporate software serial in order to turn the car off when the light changes to red.

You first need to decide if that is sufficient. Your car can be miles away when the traffic light turns red and should in that case probably not stop immediately. So you might need more than just serial communication.

Next you need to define a command set that both sides know about. The traffic light can e.g. send its status ('R', 'Y', 'G') to the car. You can write code for the car to handle that.

It will be the easiest to first write the car code first using Serial so you can use the Serial Monitor during development. Once that works to your satisfaction, you can replace Serial by a SoftwareSerial instance, if needed.

If you still need the car to react on buttons, you need to fix your current car code as a first step. These are the errors

C:\Users\sterretje\AppData\Local\Temp\arduino_modified_sketch_59318\sketch_dec19a.ino: In function 'void setup()':
sketch_dec19a:21: error: 'do_emergency' was not declared in this scope
   attachInterrupt(digitalPinToInterrupt(EMERGENCY_BRAKE_BUTTON), do_emergency, FALLING);
                                                                  ^

C:\Users\sterretje\AppData\Local\Temp\arduino_modified_sketch_59318\sketch_dec19a.ino: In function 'void loop()':
sketch_dec19a:26: error: 'StateVariable' was not declared in this scope
   switch (StateVariable); {
           ^
sketch_dec19a:27: error: case label '0' not within a switch statement
   case IDLE_STATE:
   ^
sketch_dec19a:28: error: 'PhaseVariable' was not declared in this scope
     switch (PhaseVariable) {
             ^
sketch_dec19a:40: error: 'StateVariable' was not declared in this scope
         StateVariable = DRIVING_STATE;
         ^
sketch_dec19a:44: error: break statement not within loop or switch
     break;
     ^
sketch_dec19a:45: error: case label '1' not within a switch statement
   case DRIVING_STATE:
   ^
sketch_dec19a:46: error: 'PhaseVariable' was not declared in this scope
     switch (PhaseVariable) {
             ^
sketch_dec19a:49: error: 'Car_INACTIVE_LED' was not declared in this scope
         digitalWrite(Car_INACTIVE_LED, HIGH);
                      ^
sketch_dec19a:58: error: expected primary-expression before ')' token
           )
           ^
sketch_dec19a:67: error: 'StateVariable' was not declared in this scope
             StateVariable = IDLE_STATE;
             ^

exit status 1
'do_emergency' was not declared in this scope