//Flow control
#define METHOD_STEP 5
int counter = 0;
int checksum = ~(2*METHOD_STEP);

void setup(){
  //Initialize the LCD and the LEDs:
  lcd.init();
  lcd.backlight();
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
}

//Random delay
void delayR(){
  int loops = rand() & 0x3FF;
  while (--loops >= 0 ) {
  loops++;
  loops--;
 }
 counter += METHOD_STEP;
}

int Lane1[] = {13,12,11}; // Lane 1 Red, Yellow and Green
int Lane2[] = {10,9,8};// Lane 2 Red, Yellow and Green
int Lane3[] = {7,6,5};// Lane 3 Red, Yellow and Green
int Lane4[] = {4,3,2};// Lane 4 Red, Yellow and Green

void setup() 
{
  int i, j;
  for (i = 0; i < 3; i++)
  {
    pinMode(Lane1[i], OUTPUT); 
    pinMode(Lane2[i], OUTPUT);
    pinMode(Lane3[i], OUTPUT);
    pinMode(Lane4[i], OUTPUT);
  }

  //Execution of loop
  if(i != 3)
    return false;
  delayR();
  for (j = 0; j < 3; j++)
  {
    digitalWrite(Lane1[j], LOW); 
    digitalWrite(Lane2[j], LOW);
    digitalWrite(Lane3[j], LOW);
    digitalWrite(Lane4[j], LOW);
  }

  //Execution of loop
  if(j != 3)
    return false;
  delayR();

  //Verify sensitive data
  if(counter != 2*METHOD_STEP){
    if(checksum != ~(counter))
      return false;
  }
}

void loop() 
 {
  //Lane 1 goes Green
  digitalWrite(Lane1[2], HIGH);
  digitalWrite(Lane3[0], HIGH);
  digitalWrite(Lane4[0], HIGH);
  digitalWrite(Lane2[0], HIGH);
  lcd.setCursor(6, 0);
  //To avoid residual writing on LCD:
  lcd.println("GO!");
  delay(5000);

  digitalWrite(Lane1[2], LOW);
  digitalWrite(Lane3[0], LOW);
  digitalWrite(Lane1[1], HIGH);
  digitalWrite(Lane3[1], HIGH);
  delay(2000);

  //Lane 3 goes Green
  digitalWrite(Lane1[1], LOW);
  digitalWrite(Lane3[1], LOW);
  digitalWrite(Lane1[0], HIGH);
  digitalWrite(Lane3[2], HIGH);
  delay(5000);

  digitalWrite(Lane3[2], LOW);
  digitalWrite(Lane4[0], LOW);
  digitalWrite(Lane3[1], HIGH);
  digitalWrite(Lane4[1], HIGH);
  delay(2000);

  //Lane 4 goes Green
  digitalWrite(Lane3[1], LOW);
  digitalWrite(Lane4[1], LOW);
  digitalWrite(Lane3[0], HIGH);
  digitalWrite(Lane4[2], HIGH);
  delay(5000);

  digitalWrite(Lane4[2], LOW);
  digitalWrite(Lane2[0], LOW);
  digitalWrite(Lane4[1], HIGH);
  digitalWrite(Lane2[1], HIGH);
  delay(2000);

  //Lane 2 goes Green
  digitalWrite(Lane4[1], LOW);
  digitalWrite(Lane2[1], LOW);
  digitalWrite(Lane4[0], HIGH);
  digitalWrite(Lane2[2], HIGH);
  delay(5000);

  digitalWrite(Lane1[0], LOW);
  digitalWrite(Lane2[2], LOW);
  digitalWrite(Lane1[1], HIGH);
  digitalWrite(Lane2[1], HIGH);
  delay(2000);

  digitalWrite(Lane2[1], LOW);
  digitalWrite(Lane1[1], LOW);
 }