Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // TrafficLight.ino
- //
- // 2023 trent m. wyatt
- //
- // example traffic light system for 3-sided lights
- //
- enum MagicNumbers {
- // alias' for the 3 sides
- N = 0,
- E = 1,
- S = 2,
- // alias' for the two sets of traffic: NS and EW
- NS = 0,
- EW = 1,
- // alias' for the 3 colors
- GREEN = 0,
- YELLOW = 1,
- RED = 2,
- // motion sensor pin at 12
- motionSensorPin = 12,
- };
- //
- // LED pin definitions array:
- //
- int pins[3][3];
- //
- // Global Variables
- //
- bool motionDetected = false;
- //
- // Current traffic flow
- //
- int flowing = NS;
- //
- // Preset Color Patterns:
- // G Y R
- int greenOnly[3] = { HIGH, LOW, LOW };
- int yellowOnly[3] = { LOW, HIGH, LOW };
- int redOnly[3] = { LOW, LOW, HIGH };
- int yellowGreen[3] = { HIGH, HIGH, LOW };
- //
- // set the 3 lights on one of the sides
- //
- void set_side(int dir, int colors[3]) {
- for (int color = GREEN; color <= RED; color++) {
- digitalWrite(pins[dir][color], colors[color]);
- }
- }
- //
- // Sets the current flow of traffic to the specified colors
- //
- void set_green() {
- if (flowing == NS) {
- set_side(N, greenOnly);
- set_side(E, redOnly);
- set_side(S, greenOnly);
- }
- else {
- set_side(N, redOnly);
- set_side(E, greenOnly);
- set_side(S, redOnly);
- }
- }
- void set_caution() {
- if (flowing == NS) {
- set_side(N, yellowGreen);
- set_side(S, yellowGreen);
- }
- else {
- set_side(E, yellowGreen);
- }
- }
- void change_flow() {
- if (flowing == NS) {
- flowing = EW;
- }
- else {
- flowing = NS;
- }
- }
- void setup() {
- delay(500);
- Serial.begin(115200);
- delay(500);
- // configure the input pin
- pinMode(motionSensorPin, INPUT);
- // configure the output pins
- for (int side = N; side <= S; side++) {
- for (int color = GREEN; color <= RED; color++) {
- // calculate the pin #
- int pin = color + (side * 3) + 2;
- // set the pin mode: (INPUT, INPUT_PULLUP, or OUTPUT)
- pinMode(pin, OUTPUT);
- // remember the pin numbers
- pins[side][color] = pin;
- }
- }
- set_green();
- }
- void loop() {
- motionDetected = digitalRead(motionSensorPin);
- if (motionDetected) {
- set_caution(); // sets green and yellow in the current flow direction
- delay(5000);
- change_flow(); // change from NS flow to EW or from EW to NS flow
- set_green(); // sets green in current flow direction and red in the other direction
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement