AR-3Boshlang‘ich

Traffic Light

4.8(137)
440 bajarildi
Traffic Light
A tiny copy of the traffic light you see on the road every day. Red stays on for two seconds, yellow flashes for a moment, green stays on for two seconds, then it goes back to red through yellow again, over and over. By switching three LEDs on and off in turn, you see how timing is put together.

Video

Elektr sxemasi

Traffic Light - Elektr sxemasi

Manba kodi

C++ (Arduino IDE)
1// ─────────────────────────────────────────
2//   BlueGrays · bluegrays.com
3//   Traffic Light
4// ─────────────────────────────────────────
5// Traffic light cycle with red, yellow and green LEDs: red 2 s, yellow 0.3
6// s, green 2 s, yellow 0.3 s, then it starts over.
7//
8// Pins:
9//   D2 -> Red LED
10//   D3 -> Yellow LED
11//   D4 -> Green LED
12//   Each LED with a 330 ohm resistor
13
14void setup() {
15  pinMode(2,OUTPUT);    // Red
16  pinMode(3,OUTPUT);    // Yellow
17  pinMode(4,OUTPUT);    // Green
18}
19
20void loop() {
21  // Red on, wait 2 s
22  digitalWrite(2,HIGH);
23  digitalWrite(3,LOW);
24  digitalWrite(4,LOW);
25  delay(2000);
26  // Yellow on, wait 0.3 s
27  digitalWrite(2,LOW);
28  digitalWrite(3,HIGH);
29  digitalWrite(4,LOW);
30  delay(300);
31  // Green on, wait 2 s
32  digitalWrite(2,LOW);
33  digitalWrite(3,LOW);
34  digitalWrite(4,HIGH);
35  delay(2000);
36  // Yellow on, then back to red
37  digitalWrite(2,LOW);
38  digitalWrite(3,HIGH);
39  digitalWrite(4,LOW);
40  delay(300);
41}
42

Ko‘p so‘raladigan savollar

How long should the yellow light at a traffic light stay on?

In real traffic lights, the yellow light usually stays on for 3–4 seconds. In the project, this duration is set using the `delay()` function; if the red and green lights are kept on longer and the yellow light is kept on shorter, a cycle that closely resembles reality is achieved.

Why is a 330 Ω resistor used instead of a 220 Ω one?

A 330 Ω resistor reduces the current slightly (to about 9–10 mA); the LEDs are still clearly visible, and less total current is drawn from the pins. It also works with a 220 Ω resistor; the LEDs are just a little brighter.

Can I add a pedestrian button?

Yes. You can add a push button and a 10 kΩ pull-down resistor and read it using `digitalRead`. When the button is pressed, you can switch the loop to red and turn on a separate green LED for pedestrians; using `millis()` instead of `delay` ensures that the button is detected immediately.

The order of the LEDs is mixed up—what should I do?

Compare the pin definitions in the code (red, yellow, green) with the wires on the circuit one by one. The easiest way is to light up each LED using a separate test code and verify which pin it is connected to.