TinkerKit Tutorial: Basics: 11 – First block test: Traffic Light (Solution)

Basic Lessons:

  1. Introduction
  2. Project Setup
  3. Arduino Software
  4. Starting with the code
  5. Sensors and Actuators
  6. Button & IF statement
  7. Serial Communication
  8. Connect Sensors and Actuators
  9. Button States
  10. FOR Loop
  11. Traffic Light

We used one light sensor and four leds: three for the cars and one for pedestrians.

TKLed pedGreen(O0);
TKLed carYellow(O1);
TKLed carRed(O2);
TKLed carGreen(O3);
TKLightSensor action(I0);

The light sensor is covered with paper: the more you hide the electronics behind the scene, the more “magic” your final project will result.

Basically we divided our code in two parts: one for the regular traffic and one for pedestrians that is executed only when they call for the green light. We did everything just with an if and some delays. If the values read were under a certain treshold (in our case is 100 but each sensor reads different values in different contexts, use the Serial.print to see the readings and choose the proper value), the pedestrian code is executed.

The light for cars is always green until something happens so our void loop looks like:

void loop() {
    carGreen.on();
    val = action.read();

    if (val < 100) {
        //red for cars and green for pedestrians    
    }
}

We want to turn the traffic light to yellow and then red, while the one for pedestrian should become green.

carGreen.off();
carYellow.on();
delay(3000);

carYellow.off();
carRed.on();

pedGreen.on();
delay(4000);

It’s better if we warn the pedestrians before the light turns back off, so that they can hurry to reach the other side of the crossroad. We have only one LED, so we decided to make it blink:

for(int i=0; i<7; i++) {
  pedGreen.off();
  delay(200);  
  pedGreen.on();
  delay(200);  
}

after the flashing light, we turn everything off:

carRed.off();
pedGreen.off();

and that’s basically our code.

Here’s the full version:

#include <TinkerKit.h>

TKLed carRed(O2);
TKLed carYellow(O1);
TKLed carGreen(O3);

TKLed pedGreen(O0);

TKLightSensor action(I0);
int val;

void setup() {
  Serial.begin(9600);
}

void loop() {
  carGreen.on();

  val = action.read();

  if (val < 100) {

    carGreen.off();
    carYellow.on();
    delay(3000);

    carYellow.off();
    carRed.on();
    pedGreen.on();
    delay(4000);

    for(int i=0; i<7; i++) {
      pedGreen.off();
      delay(200);  
      pedGreen.on();
      delay(200);  
    }

    carRed.off();
    pedGreen.off();
  }
}

Prev Section: Traffic Light

Leave a Reply

Your email address will not be published. Required fields are marked *