Arduino实践:人行横道按键控制红绿灯

Arduino例程,环境: Arduino学习平台搭建配置方式(一)

//模拟路口按键控制人行横道红绿灯
int redLEDPin = 6;
int greenLEDPin = 9;
int redLED2Pin = 10;
int greenLED2Pin = 13;
int buzzerPin = 15;//外接无源蜂鸣器
int switchPin = 2;
int switchValue = 1;

void setup() {
  // put your setup code here, to run once:
  pinMode(redLEDPin, OUTPUT);
  pinMode(greenLEDPin, OUTPUT);
  pinMode(redLED2Pin, OUTPUT);
  pinMode(greenLED2Pin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  pinMode(switchPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  switchValue = digitalRead(switchPin);
  //Serial.print("switchValue=");
  //Serial.println(switchValue);
  if (switchValue == LOW) {
    digitalWrite(greenLEDPin, HIGH);
    digitalWrite(redLEDPin, LOW);
    digitalWrite(redLED2Pin, HIGH);
    digitalWrite(greenLED2Pin, LOW);
  }
  else {
    //按下按键,主道红绿灯变黄变红,人行横道红绿灯变绿
    digitalWrite(greenLEDPin, HIGH);
    digitalWrite(redLEDPin, HIGH);
    delay(1000);
    digitalWrite(greenLEDPin, LOW);
    digitalWrite(redLED2Pin, LOW);
    digitalWrite(greenLED2Pin, HIGH);
    delay(5000);
    //人行横道红绿灯提示尽快通过
    for (int i = 0; i < 10; i++) {
      digitalWrite(greenLED2Pin, HIGH);
      alarm();
      digitalWrite(greenLED2Pin, LOW);
      alarm();
    }
  }
}
//蜂鸣器
void alarm() {
  for (int i = 0; i < 50; i++) {
    digitalWrite(buzzerPin, HIGH);
    delay(1);
    digitalWrite(buzzerPin, LOW);
    delay(1);
  }
}