Lab 4 - EENG312
Lab 4 - EENG312
Objective: The students will be introduced to the concept of non-blocking code using the
millis() function for time control. The students will get to practice the usage of flags to check
the progress of the code.
Lab Work: Each group of students will edit and run the following Program in the IDE and
Tinkercad and debug to make it ready to be uploaded to Arduino Uno. The program controls
one set of traffic lights for cars and another for pedestrians. A pedestrian button can be used
to allow pedestrians to cross.
//traffic light code
//millis for time control allowing non-blocking code
//pedestrian button
#define car_red 4
#define car_yellow 3
#define car_green 2
#define ped_green 5
#define ped_red 6
#define ped_button 8
}
else if (current_time > 4500 && current_time < 5000)
{
digitalWrite(ped_red,HIGH);
digitalWrite(ped_green,LOW);
}
else if (current_time > 5000 && current_time < 6000)
{
digitalWrite(car_yellow, HIGH);
}
else if (current_time > 6000 && current_time < 9000)
{
digitalWrite(car_red, LOW);
digitalWrite(car_yellow, LOW);
digitalWrite(car_green,HIGH);
}
else if (current_time > 9000 && current_time < 10000)
{
digitalWrite(car_green,LOW);
digitalWrite(car_yellow, HIGH);
}
//the sequence takes 10 seconds. After 10 seconds it must
//restart, thus we turn the start flag to 1
else if (current_time > 10000)
{
start = 1;
}
}
void setup()
{
//Serial.begin(9600);
pinMode(car_red, OUTPUT);
pinMode(car_yellow, OUTPUT);
pinMode(car_green, OUTPUT);
pinMode(ped_green, OUTPUT);
pinMode(ped_red, OUTPUT);
pinMode(ped_button, INPUT);
//start = 1 -> light sequence will reset
//start = 0 -> light sequence will continue from
// where it was
start = 1;
}
void loop()
{
button_pressed = digitalRead(ped_button);
if (button_pressed == HIGH)
{
//Pedestrians are trying to cross
//when button is pressed, the light sequence is
//reset, turning lights red
start_time = millis();
start = 0;
else
{
//Routine
if (start == 1)
{
//reseting start time to now and start flag to 0
//starts the light sequence from red
start_time = millis();
start = 0;
}
normal_lights(start_time);
delay(10);
}
HW 4. (Due Friday after Midterm Exams)
Write a program with the respective Tinkercad circuit design to control traffic lights like the
example above. In addition to the example setup, you must have a sensor to check for
incoming cars before allowing pedestrian crossing. You could use PIR or Ultrasonic distance
sensors.
An example design would be:
No alteration to light sequence if cars are detected.
Reset light sequence if there are no cars (resets to ‘red for cars’ allowing crossing)
HINT: PIR sensor detects motion.
HINT: Ultrasonic distance sensor measures distance in terms of time.