一、电路图
二、代码
管脚号 | 功能 |
---|---|
D2 | 红灯 |
D3 | 绿灯 |
D4 | 黄灯 |
void setup() {
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
}
void loop() {
digitalWrite(2,HIGH);
digitalWrite(3,LOW);
digitalWrite(4,LOW);
delay(3000);
for(int i=0;i<7;i++)
{
digitalWrite(2,LOW);
digitalWrite(3,LOW);
digitalWrite(4,HIGH);
delay(200);
digitalWrite(2,LOW);
digitalWrite(3,LOW);
digitalWrite(4,LOW);
delay(200);
}
digitalWrite(2,LOW);
digitalWrite(3,HIGH);
digitalWrite(4,LOW);
delay(4000);
}
改良了一下
#define red 1
#define yellow 2
#define green 3
int LedRed=2;
int LedYellow=4;
int LedGreen=3;
void setup()
{
pinMode(10,OUTPUT);
pinMode(7,OUTPUT);
pinMode(4,OUTPUT);
}
void loop()
{
trafficLights(red);
trafficLights(green);
trafficLights(yellow);
}
void trafficLights(int light)
{
switch(light)
{
case 1: digitalWrite(LedRed,HIGH);
digitalWrite(LedYellow,LOW);
digitalWrite(LedGreen,LOW);
delay(4000);
break;
case 2:
for(int i=0;i<7;i++)
{
digitalWrite(LedRed,LOW);
digitalWrite(LedYellow,HIGH);
digitalWrite(LedGreen,LOW);
delay(200);
digitalWrite(LedRed,LOW);
digitalWrite(LedYellow,LOW);
digitalWrite(LedGreen,LOW);
delay(200);
}
break;
case 3: digitalWrite(LedRed,LOW);
digitalWrite(LedYellow,LOW);
digitalWrite(LedGreen,HIGH);
delay(4000);
break;
default: break;
}
}