Saturday, March 4, 2017

17. Semáforo (4)

Quando o botão é apertado o estado do pin 5 passa de HIGH (definida com INPUT_PULLUP) para LOW, de modo que o semáforo passa a funcionar. Se o botão é solto o estado se congela.

Baseado em:
Simon Monk, 30 Arduino Projects for the Evil Genius, McGraw-Hill Education TAB; 2nd ed., 2013. 

int redPin = 4;
int yellowPin = 3;
int greenPin = 2;
int buttonPin = 5;

int state = 0;

void setup()                    
{
  pinMode(redPin, OUTPUT);    
  pinMode(yellowPin, OUTPUT);    
  pinMode(greenPin, OUTPUT);     
  pinMode(buttonPin, INPUT_PULLUP); 
}

void loop()                    
{
  if (digitalRead(buttonPin) == LOW)
  {
    if (state == 0)
    {
      setLights(HIGH, LOW, LOW);
      state = 1;
      delay(3000);
    }
    else if (state == 1)
    {
      setLights(HIGH, HIGH, LOW);
      state = 2;
      delay(2000);
    }
    else if (state == 2)
    {
      setLights(LOW, LOW, HIGH);
      state = 3;
      delay(3000);
    }
    else if (state == 3)
    {
      setLights(LOW, HIGH, LOW);
      state = 0;
      delay(2000);
    }
    delay(1000);
  }
}

void setLights(int red, int yellow, int green)
{
  digitalWrite(redPin, red);
  digitalWrite(yellowPin, yellow);
  digitalWrite(greenPin, green);
}  





Exercício: 

1. Simule este circuito em Tinkercad e depois implemente-o físicamente.

No comments:

Post a Comment