From b867497b51f7a350ef32ad93a0dcd029d5a16d38 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 23 Oct 2025 00:14:20 +0000 Subject: [PATCH] Add comprehensive documentation for all Arduino projects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Created detailed README files for the repository and each learning project: - Main README with project overview and learning path - Lesson 1: Button controlled LED with circuit diagrams and concepts - Lesson 2: For loop LED sequence with code explanations - Stop Light: Traffic light simulator with interrupt handling - LED Distance: NeoPixel distance indicator with sensor integration Each README includes hardware requirements, wiring diagrams, code explanations, troubleshooting tips, and learning extensions. ðŸĪ– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- README.md | 99 +++++++++ learning/led_distance/README.md | 347 ++++++++++++++++++++++++++++++++ learning/lesson1/README.md | 121 +++++++++++ learning/lesson2/README.md | 199 ++++++++++++++++++ learning/stop_light/README.md | 272 +++++++++++++++++++++++++ 5 files changed, 1038 insertions(+) create mode 100644 README.md create mode 100644 learning/led_distance/README.md create mode 100644 learning/lesson1/README.md create mode 100644 learning/lesson2/README.md create mode 100644 learning/stop_light/README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..e894583 --- /dev/null +++ b/README.md @@ -0,0 +1,99 @@ +# Arduino Learning Projects + +A collection of Arduino sketches for learning microcontroller programming and electronics. This repository contains progressively advanced projects that demonstrate various Arduino concepts and techniques. + +## Projects Overview + +### 1. Lesson 1 - Button Controlled LED +**Location:** `learning/lesson1/` +**Difficulty:** Beginner +**Concepts:** Digital input/output, button debouncing + +A basic project that demonstrates how to read a button input and control an LED. When the button is pressed, the LED turns on; when released, it turns off. + +[View Project Details](learning/lesson1/README.md) + +### 2. Lesson 2 - LED For Loop +**Location:** `learning/lesson2/` +**Difficulty:** Beginner +**Concepts:** For loops, sequential control, timing + +Demonstrates the use of for loops to control multiple LEDs in sequence. The sketch lights up 6 LEDs in order from low to high pin numbers, then reverses the pattern. + +[View Project Details](learning/lesson2/README.md) + +### 3. Traffic Light with Crosswalk +**Location:** `learning/stop_light/` +**Difficulty:** Intermediate +**Concepts:** Interrupts, state management, complex timing patterns + +A traffic light simulator with pedestrian crosswalk functionality. Features a button-activated crosswalk that triggers when the traffic light is red, complete with flashing warning signals. + +[View Project Details](learning/stop_light/README.md) + +### 4. LED Distance Indicator +**Location:** `learning/led_distance/` +**Difficulty:** Advanced +**Concepts:** External libraries, sensor integration, color mapping, analog output + +An advanced project using an HC-SR04 ultrasonic sensor to measure distance and display it visually on a NeoPixel LED strip. The color gradually transitions from red (close) to green (far) based on distance measurements. + +[View Project Details](learning/led_distance/README.md) + +## Getting Started + +### Prerequisites + +- Arduino IDE (download from [arduino.cc](https://www.arduino.cc/en/software)) +- Arduino board (Uno, Nano, or compatible) +- Basic electronic components (LEDs, resistors, buttons, breadboard, jumper wires) +- For advanced projects: NeoPixel strip, HC-SR04 sensor + +### Installation + +1. Clone this repository: + ```bash + git clone + cd arduino + ``` + +2. Open the desired project's `.ino` file in Arduino IDE + +3. Connect your Arduino board via USB + +4. Select your board and port from Tools menu + +5. Upload the sketch to your Arduino + +### Required Libraries + +Some projects require external libraries: + +- **led_distance**: [Adafruit NeoPixel Library](https://github.com/adafruit/Adafruit_NeoPixel) + +Install libraries through Arduino IDE: Sketch → Include Library → Manage Libraries + +## Learning Path + +These projects are designed to be completed in order, with each building on concepts from previous lessons: + +1. Start with **Lesson 1** to understand basic digital I/O +2. Progress to **Lesson 2** to learn control structures +3. Move to **Stop Light** to explore interrupts and state management +4. Complete **LED Distance** to work with sensors and external libraries + +## Contributing + +This is a personal learning repository. Feel free to fork and adapt these projects for your own learning journey. + +## License + +The code in this repository includes examples from the Arduino community and original work: +- Lesson 1 and 2 are based on official Arduino tutorials (Public Domain) +- Stop Light and LED Distance are original projects by Joshua Shanks + +## Additional Resources + +- [Arduino Official Tutorials](https://www.arduino.cc/en/Tutorial/HomePage) +- [Arduino Language Reference](https://www.arduino.cc/reference/en/) +- [Arduino Forum](https://forum.arduino.cc/) diff --git a/learning/led_distance/README.md b/learning/led_distance/README.md new file mode 100644 index 0000000..9cb39ca --- /dev/null +++ b/learning/led_distance/README.md @@ -0,0 +1,347 @@ +# LED Distance Indicator with NeoPixels + +An advanced Arduino project that uses an HC-SR04 ultrasonic sensor to measure distance and displays it visually on an Adafruit NeoPixel LED strip with color-coded feedback. + +## Overview + +This project teaches advanced Arduino concepts: +- Integrating external libraries +- Working with ultrasonic sensors +- Controlling addressable RGB LEDs (NeoPixels) +- Color mapping and interpolation +- Sensor smoothing and noise reduction +- Serial communication for debugging + +## Hardware Required + +- Arduino board (Uno, Nano, or compatible) +- HC-SR04 Ultrasonic Distance Sensor +- Adafruit NeoPixel LED strip (8 pixels) +- Breadboard and jumper wires +- External 5V power supply for NeoPixels (recommended for strips > 8 LEDs) + +## Required Libraries + +This sketch requires the Adafruit NeoPixel library: + +**Installation:** +1. Open Arduino IDE +2. Go to Sketch → Include Library → Manage Libraries +3. Search for "Adafruit NeoPixel" +4. Install the latest version + +**Or download from:** +https://github.com/adafruit/Adafruit_NeoPixel + +## Circuit Diagram + +### NeoPixel Connections + +- NeoPixel Data IN → Pin 10 +- NeoPixel VCC → 5V (use external power for longer strips) +- NeoPixel GND → GND + +**Important:** For strips with more than 8 pixels, use an external 5V power supply. Connect Arduino GND to power supply GND (common ground). + +### HC-SR04 Sensor Connections + +- VCC → 5V +- GND → GND +- TRIG → Pin 4 +- ECHO → Pin 5 + +## How It Works + +### Distance Measurement + +The HC-SR04 sensor measures distance using ultrasound: +1. Trigger pin sends out ultrasonic pulse +2. Sound waves bounce off objects +3. Echo pin receives the reflection +4. Distance = (time × speed of sound) / 2 + +### Visual Feedback + +The NeoPixel strip changes color based on distance: + +| Distance | Color | Meaning | +|----------|-------|---------| +| < 10 cm | Red | Too close! | +| 10-35 cm | Red → Yellow | Getting closer | +| 35-60 cm | Yellow → Green | Safe distance | +| > 60 cm | Green | Far away | + +Color smoothly transitions between states for intuitive feedback. + +### Noise Reduction + +The sketch includes smoothing to prevent flickering: +- Limits rapid distance changes to Âą10 cm between readings +- Reduces sensor noise and jitter +- Creates more stable visual output + +## Code Explanation + +### Configuration +```cpp +#define LED_PIN 10 // NeoPixel data pin +#define TRIG 4 // Ultrasonic trigger +#define ECHO 5 // Ultrasonic echo + +#define MARGIN 10 // Max change between readings (cm) +#define CLOSE 10 // Red threshold (cm) +#define FAR 60 // Green threshold (cm) + +// Initialize 8-pixel strip +Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, LED_PIN, NEO_GRB + NEO_KHZ800); +``` + +### Distance Measurement +```cpp +long getDistance() { + long duration, distance; + + // Send 10Ξs pulse + digitalWrite(TRIG, LOW); + delayMicroseconds(2); + digitalWrite(TRIG, HIGH); + delayMicroseconds(10); + digitalWrite(TRIG, LOW); + + // Measure echo duration + duration = pulseIn(ECHO, HIGH); + + // Convert to centimeters + // Speed of sound: 29.1 Ξs per cm (round trip) + distance = (duration/2) / 29.1; + + return distance; +} +``` + +### Color Mapping +```cpp +void loop() { + long distance = getDistance(); + + // Smooth out noise + if(lastDistance != NULL) { + distance = constrain(distance, lastDistance - MARGIN, lastDistance + MARGIN); + } + + int mid = (CLOSE + FAR) / 2; // Midpoint = 35 cm + + // Far: pure green + if(distance > FAR) { + colorWipe(strip.Color(0, 255, 0), 0); + + // Close: pure red + } else if(distance < CLOSE) { + colorWipe(strip.Color(255, 0, 0), 0); + + // Middle range: interpolate colors + } else { + if(distance > mid) { + // Far side: fade out red, keep green + int r = map(distance, mid, FAR, 255, 0); + colorWipe(strip.Color(r, 255, 0), 0); + } else { + // Close side: fade in green, keep red + int g = map(distance, CLOSE, mid, 0, 255); + colorWipe(strip.Color(255, g, 0), 0); + } + } + + lastDistance = distance; + delay(250); // Update 4 times per second +} +``` + +### Setting All Pixels +```cpp +void colorWipe(uint32_t c, uint8_t wait) { + for(uint16_t i = 0; i < strip.numPixels(); i++) { + strip.setPixelColor(i, c); + strip.show(); + delay(wait); + } +} +``` + +## Key Concepts + +### The map() Function + +`map()` rescales a value from one range to another: + +```cpp +int r = map(distance, mid, FAR, 255, 0); +// ↑ ↑--------↑ ↑-----↑ +// value input range output range +``` + +When distance = mid (35), r = 255 (full red) +When distance = FAR (60), r = 0 (no red) + +### NeoPixel Color Format + +Colors are created with RGB values (0-255): +```cpp +strip.Color(red, green, blue) +strip.Color(255, 0, 0) // Pure red +strip.Color(0, 255, 0) // Pure green +strip.Color(255, 255, 0) // Yellow +strip.Color(128, 128, 128) // Gray +``` + +### Constrain Function + +Limits a value to a specified range: +```cpp +distance = constrain(distance, lastDistance - MARGIN, lastDistance + MARGIN); +``` + +Prevents jumps larger than Âą10 cm between readings. + +## Serial Monitor Output + +The sketch prints distance to Serial Monitor (9600 baud): +``` +37 cm +42 cm +Out of range +15 cm +``` + +Use this for debugging and calibration. + +## Customization + +### Adjust Distance Thresholds +```cpp +#define CLOSE 5 // Red at 5 cm +#define FAR 100 // Green at 100 cm +``` + +### Change Update Rate +```cpp +delay(100); // Update 10 times per second (faster) +delay(500); // Update 2 times per second (slower) +``` + +### Different Noise Filtering +```cpp +#define MARGIN 20 // Allow larger jumps +#define MARGIN 5 // More aggressive smoothing +``` + +### More Pixels +```cpp +Adafruit_NeoPixel strip = Adafruit_NeoPixel(16, LED_PIN, NEO_GRB + NEO_KHZ800); +``` + +## Challenges & Extensions + +1. **Rainbow mode**: Create a full spectrum from red → yellow → green → blue +2. **Distance display**: Show actual distance using pixel count (closer = more pixels) +3. **Proximity alarm**: Add buzzer that beeps faster when closer +4. **Multi-zone**: Different color patterns for different distance zones +5. **Motion detection**: Detect movement by tracking distance changes +6. **Animation effects**: Add sparkles, fades, or chase patterns +7. **Potentiometer control**: Adjust thresholds with analog input + +## Example Extension: Pixel Count Display + +```cpp +void loop() { + long distance = getDistance(); + + // Map distance to pixel count (0-8) + int numPixels = map(distance, CLOSE, FAR, 8, 0); + numPixels = constrain(numPixels, 0, 8); + + // Light up numPixels in red + for(int i = 0; i < strip.numPixels(); i++) { + if(i < numPixels) { + strip.setPixelColor(i, strip.Color(255, 0, 0)); + } else { + strip.setPixelColor(i, strip.Color(0, 0, 0)); + } + } + strip.show(); + + delay(250); +} +``` + +## Troubleshooting + +**NeoPixels don't light up:** +- Check data pin connection (pin 10) +- Verify power supply (5V and GND) +- Ensure library is installed +- Try strip.begin() in setup + +**Erratic colors/flickering:** +- Add decoupling capacitor (1000ΞF) across power supply +- Use external power for longer strips +- Increase MARGIN for more smoothing +- Check for loose connections + +**Distance readings incorrect:** +- Verify TRIG and ECHO pins +- Ensure sensor has clear line of sight +- Test sensor independently with Serial Monitor +- Some surfaces absorb ultrasound (fabric, foam) + +**"Out of range" errors:** +- Sensor range: 2-400 cm +- Avoid angled surfaces (reflect sound away) +- Ensure nothing blocking sensor + +**NeoPixels wrong color:** +- Some strips use NEO_RGB instead of NEO_GRB +- Try: `Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, LED_PIN, NEO_RGB + NEO_KHZ800);` + +## Power Considerations + +NeoPixels draw significant current: +- Each pixel: ~60mA at full white +- 8 pixels: up to 480mA +- Arduino USB: 500mA limit + +**For longer strips (>8 pixels):** +- Use external 5V power supply (2A or more) +- Connect Arduino GND to power supply GND +- Power NeoPixels from external supply, not Arduino + +## Safety Notes + +- Never connect NeoPixels directly to Arduino if strip has >30 pixels +- Always connect external power supply GND to Arduino GND +- Add 300-500ÎĐ resistor between Arduino and NeoPixel data line (optional but recommended) + +## Learning Outcomes + +After completing this project, you should understand: +- How to integrate and use external libraries +- Working with ultrasonic distance sensors +- Controlling addressable RGB LEDs +- Color space manipulation and interpolation +- The map() and constrain() functions +- Sensor noise reduction techniques +- Serial debugging for sensor projects + +## References + +- HC-SR04 code adopted from: http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/ +- NeoPixel library: https://github.com/adafruit/Adafruit_NeoPixel +- Adafruit NeoPixel guide: https://learn.adafruit.com/adafruit-neopixel-uberguide + +## Author + +Joshua Shanks + +## License + +Original work - free to use and modify diff --git a/learning/lesson1/README.md b/learning/lesson1/README.md new file mode 100644 index 0000000..2e55594 --- /dev/null +++ b/learning/lesson1/README.md @@ -0,0 +1,121 @@ +# Lesson 1 - Button Controlled LED + +A basic Arduino sketch that demonstrates digital input and output by controlling an LED with a pushbutton. + +## Overview + +This project teaches fundamental Arduino concepts: +- Reading digital input from a button +- Writing digital output to an LED +- Using pinMode to configure pins +- Basic if/else control flow + +## Hardware Required + +- Arduino board (Uno, Nano, or compatible) +- LED (or use built-in LED on pin 13) +- Pushbutton +- 10K ohm resistor (for pull-down) +- 220 ohm resistor (for LED, if using external LED) +- Breadboard and jumper wires + +## Circuit Diagram + +### Connections + +**LED:** +- LED positive (long leg) → Pin 13 +- LED negative (short leg) → 220ÎĐ resistor → GND + +**Note:** Most Arduino boards have a built-in LED on pin 13, so you can test without an external LED. + +**Button:** +- One side of button → +5V +- Same side of button → 10K resistor → GND +- Other side of button → Pin 2 + +The 10K resistor acts as a pull-down resistor, ensuring the pin reads LOW when the button is not pressed. + +## How It Works + +1. **Setup Phase:** + - Pin 13 (LED) is configured as OUTPUT + - Pin 2 (button) is configured as INPUT + +2. **Loop Phase:** + - Read the button state from pin 2 + - If button is pressed (HIGH): + - Turn LED ON + - If button is not pressed (LOW): + - Turn LED OFF + +## Code Explanation + +```cpp +const int buttonPin = 2; // Button connected to pin 2 +const int ledPin = 13; // LED connected to pin 13 + +int buttonState = 0; // Variable to store button state + +void setup() { + pinMode(ledPin, OUTPUT); // Set LED pin as output + pinMode(buttonPin, INPUT); // Set button pin as input +} + +void loop() { + buttonState = digitalRead(buttonPin); // Read button state + + if (buttonState == HIGH) { + digitalWrite(ledPin, HIGH); // Turn LED on + } else { + digitalWrite(ledPin, LOW); // Turn LED off + } +} +``` + +## Key Concepts + +### Digital I/O +- **digitalRead()**: Reads the state of a digital pin (HIGH or LOW) +- **digitalWrite()**: Sets a digital pin to HIGH or LOW +- **pinMode()**: Configures a pin as INPUT or OUTPUT + +### Pull-down Resistor +The 10K resistor connected to ground ensures the input pin has a defined state (LOW) when the button is not pressed. Without this resistor, the pin would "float" and give unpredictable readings. + +## Challenges & Extensions + +Once you understand this basic sketch, try these modifications: + +1. **Reverse the behavior**: Make the LED turn off when button is pressed +2. **Add more LEDs**: Control multiple LEDs with the same button +3. **Toggle mode**: Make the LED toggle on/off with each button press (requires debouncing) +4. **Blink on press**: Make the LED blink while the button is held + +## Troubleshooting + +**LED doesn't light up:** +- Check LED polarity (long leg = positive) +- Verify LED is connected to pin 13 +- Test with built-in LED on pin 13 + +**LED always on or always off:** +- Check button wiring +- Verify pull-down resistor is connected +- Test button with multimeter + +**Erratic behavior:** +- Button may need debouncing (add 0.1ΞF capacitor across button) +- Check for loose connections + +## Source + +Based on the official Arduino Button tutorial: +http://www.arduino.cc/en/Tutorial/Button + +Modified by Tom Igoe (2011) +Original by DojoDave (2005) + +## License + +Public Domain diff --git a/learning/lesson2/README.md b/learning/lesson2/README.md new file mode 100644 index 0000000..0e4b4c3 --- /dev/null +++ b/learning/lesson2/README.md @@ -0,0 +1,199 @@ +# Lesson 2 - For Loop LED Sequence + +An Arduino sketch demonstrating the use of for loops to control multiple LEDs in sequence, creating a "Knight Rider" or "Cylon" scanning effect. + +## Overview + +This project teaches intermediate Arduino concepts: +- Using for loops for iteration +- Controlling multiple outputs programmatically +- Creating timing-based animations +- Efficient pin initialization + +## Hardware Required + +- Arduino board (Uno, Nano, or compatible) +- 6 LEDs +- 6x 220 ohm resistors +- Breadboard and jumper wires + +## Circuit Diagram + +### Connections + +Connect 6 LEDs to pins 2 through 7: + +**For each LED (repeat for pins 2-7):** +- Arduino Pin (2-7) → 220ÎĐ resistor → LED positive (long leg) +- LED negative (short leg) → GND + +All LEDs should share a common ground connection on the breadboard. + +## How It Works + +1. **Setup Phase:** + - Uses a for loop to configure pins 2-7 as OUTPUT + - Demonstrates efficient initialization of multiple pins + +2. **Loop Phase:** + - **Forward sequence**: Lights LEDs from pin 2 to pin 7 + - Each LED turns on, delays, then turns off + - **Reverse sequence**: Lights LEDs from pin 7 to pin 2 + - Creates a scanning/bouncing effect + +## Code Explanation + +```cpp +int timer = 100; // Delay in milliseconds (controls speed) + +void setup() { + // Initialize all pins as outputs using a for loop + for (int thisPin = 2; thisPin < 8; thisPin++) { + pinMode(thisPin, OUTPUT); + } +} + +void loop() { + // Forward sequence: pins 2 → 7 + for (int thisPin = 2; thisPin < 8; thisPin++) { + digitalWrite(thisPin, HIGH); // Turn on + delay(timer); // Wait + digitalWrite(thisPin, LOW); // Turn off + } + + // Reverse sequence: pins 7 → 2 + for (int thisPin = 7; thisPin >= 2; thisPin--) { + digitalWrite(thisPin, HIGH); // Turn on + delay(timer); // Wait + digitalWrite(thisPin, LOW); // Turn off + } +} +``` + +## Key Concepts + +### For Loops + +For loops have three parts: +1. **Initialization**: `int thisPin = 2` - sets starting value +2. **Condition**: `thisPin < 8` - loop continues while true +3. **Increment**: `thisPin++` - updates variable each iteration + +```cpp +for (initialization; condition; increment) { + // Code to repeat +} +``` + +### Incrementing vs Decrementing +- `thisPin++` increases by 1 (forward sequence) +- `thisPin--` decreases by 1 (reverse sequence) + +### Loop Boundaries +- Forward: `thisPin < 8` means loop runs for values 2, 3, 4, 5, 6, 7 +- Reverse: `thisPin >= 2` means loop runs for values 7, 6, 5, 4, 3, 2 + +## Adjusting the Speed + +Change the `timer` variable to adjust animation speed: +- Smaller values = faster (e.g., `50`) +- Larger values = slower (e.g., `200`) + +```cpp +int timer = 50; // Fast animation +``` + +## Challenges & Extensions + +Try these modifications to enhance your learning: + +1. **Different patterns**: + - Light all LEDs at once, then turn off in sequence + - Random LED selection + - Binary counter (LEDs represent binary digits) + +2. **Variable speed**: + - Make the animation speed up and slow down + - Use potentiometer to control speed with analogRead() + +3. **Persistence**: + - Leave LEDs on instead of turning them off + - Create a "fill up" effect + +4. **More LEDs**: + - Extend to use pins 2-13 for 12 LEDs + +## Example Modifications + +### Leave LEDs on (fill up effect): +```cpp +void loop() { + // Turn on LEDs one by one + for (int thisPin = 2; thisPin < 8; thisPin++) { + digitalWrite(thisPin, HIGH); + delay(timer); + } + + // Turn off LEDs one by one + for (int thisPin = 2; thisPin < 8; thisPin++) { + digitalWrite(thisPin, LOW); + delay(timer); + } +} +``` + +### All on, then sequential off: +```cpp +void loop() { + // Turn all on + for (int thisPin = 2; thisPin < 8; thisPin++) { + digitalWrite(thisPin, HIGH); + } + delay(timer); + + // Turn off one by one + for (int thisPin = 2; thisPin < 8; thisPin++) { + digitalWrite(thisPin, LOW); + delay(timer); + } +} +``` + +## Troubleshooting + +**No LEDs light up:** +- Check power connections (GND) +- Verify LED polarity (long leg = positive) +- Test each LED individually + +**Only some LEDs work:** +- Check resistor connections +- Verify pin numbers in code match hardware + +**LEDs are dim:** +- Resistor value may be too high +- Try 150ÎĐ or 220ÎĐ resistors + +**Sequence is wrong:** +- Verify loop boundaries (< 8, >= 2) +- Check pin numbers + +## Learning Outcomes + +After completing this lesson, you should understand: +- How to use for loops for repetitive tasks +- Incrementing and decrementing loop counters +- Creating sequences and patterns with multiple outputs +- The relationship between delay() and animation speed + +## Source + +Based on the official Arduino For Loop tutorial: +http://www.arduino.cc/en/Tutorial/ForLoop + +Modified by Tom Igoe (2011) +Created by David A. Mellis (2006) + +## License + +Public Domain diff --git a/learning/stop_light/README.md b/learning/stop_light/README.md new file mode 100644 index 0000000..4696ca0 --- /dev/null +++ b/learning/stop_light/README.md @@ -0,0 +1,272 @@ +# Traffic Light with Crosswalk Simulator + +An intermediate Arduino project that simulates a traffic light system with pedestrian crosswalk functionality. Features button-activated crosswalk signals and interrupt-driven input. + +## Overview + +This project teaches advanced Arduino concepts: +- Hardware interrupts for responsive button handling +- State management for complex systems +- Multiple timing patterns and sequences +- Volatile variables for interrupt safety +- Coordinating multiple outputs + +## Hardware Required + +- Arduino board (Uno, Nano, or compatible) +- 5 LEDs (Red, Yellow, Green for traffic + Red, Green for walk signal) +- 5x 220 ohm resistors (for LEDs) +- Pushbutton +- 10K ohm resistor (pull-down for button) +- Breadboard and jumper wires + +## Circuit Diagram + +### LED Connections + +**Traffic Light:** +- Pin 10 → 220ÎĐ resistor → Red LED → GND +- Pin 11 → 220ÎĐ resistor → Yellow LED → GND +- Pin 12 → 220ÎĐ resistor → Green LED → GND + +**Crosswalk Signal:** +- Pin 8 → 220ÎĐ resistor → Red LED → GND +- Pin 9 → 220ÎĐ resistor → Green LED → GND + +**Button:** +- One side → +5V +- Same side → 10K resistor → GND +- Other side → Pin 2 (Interrupt 0) + +### Reference Wiring + +See example wiring diagram at: +http://fritzing.org/projects/digital-inputoutput-traffic-light/ + +## How It Works + +### Traffic Light Cycle + +The traffic light continuously cycles through: +1. Green (go) - 2.5 seconds +2. Yellow (caution) - 2.5 seconds +3. Red (stop) - 2.5 seconds +4. Back to Green + +### Crosswalk Activation + +When the crosswalk button is pressed: +1. The system waits until the traffic light turns RED +2. Walk signal turns GREEN (safe to cross) - 2.5 seconds +3. Walk signal FLASHES RED (finish crossing) - 4 quick flashes +4. Walk signal returns to solid RED + +### Interrupt-Driven Input + +The button uses hardware interrupts (interrupt 0 on pin 2): +- Button presses are detected immediately, even during delays +- No polling required - more efficient than checking in loop() +- Sets `needsWalk` flag for processing during next red light + +## Code Explanation + +### Pin Definitions +```cpp +const int RED_TRAFFIC = 10; +const int YELLOW_TRAFFIC = 11; +const int GREEN_TRAFFIC = 12; +const int RED_WALK = 8; +const int GREEN_WALK = 9; +const int BUTTON = 2; +``` + +### Key Variables +```cpp +int traffic_timer = 2500; // Time for each traffic light +int walk_timer = 2500; // Time for walk signal +int currentTrafficLight = RED_TRAFFIC; // Track current state +volatile boolean needsWalk = false; // Crosswalk request flag +``` + +**Note:** `needsWalk` is `volatile` because it's modified in an interrupt handler and read in the main loop. + +### Setup +```cpp +void setup() { + // Configure all LED pins as outputs + for(int pin = 8; pin < 13; pin++) { + pinMode(pin, OUTPUT); + } + + pinMode(BUTTON, INPUT); + + // Attach interrupt: pin 2 = interrupt 0 + attachInterrupt(0, buttonPress, CHANGE); + + digitalWrite(RED_WALK, HIGH); // Start with red walk signal +} +``` + +### Main Functions + +**Traffic Light Cycling:** +```cpp +int cycleTrafficLight(int current) { + int next = current - 1; // Move to next light + if(next < RED_TRAFFIC) { + next = GREEN_TRAFFIC; // Wrap back to green + } + digitalWrite(current, LOW); // Turn off current + digitalWrite(next, HIGH); // Turn on next + return next; +} +``` + +**Crosswalk Sequence:** +```cpp +void crosswalk() { + // Green walk signal + digitalWrite(GREEN_WALK, HIGH); + digitalWrite(RED_WALK, LOW); + delay(walk_timer); + + digitalWrite(GREEN_WALK, LOW); + + // Flash red walk signal 4 times + for(int i = 0; i < 4; i++) { + digitalWrite(RED_WALK, HIGH); + delay(walk_timer / 4); + digitalWrite(RED_WALK, LOW); + delay(walk_timer / 6); + } + + digitalWrite(RED_WALK, HIGH); + needsWalk = false; // Reset flag +} +``` + +**Interrupt Handler:** +```cpp +void buttonPress() { + needsWalk = true; // Set flag when button pressed +} +``` + +**Main Loop:** +```cpp +void loop() { + currentTrafficLight = cycleTrafficLight(currentTrafficLight); + + // Only activate crosswalk when traffic is red + if(currentTrafficLight == RED_TRAFFIC && needsWalk) { + crosswalk(); + } else { + delay(traffic_timer); + } +} +``` + +## Key Concepts + +### Hardware Interrupts + +Interrupts allow the Arduino to respond immediately to events: +- `attachInterrupt(interrupt, function, mode)` +- Interrupt 0 = Pin 2, Interrupt 1 = Pin 3 +- `CHANGE` mode triggers on any state change +- Other modes: `RISING`, `FALLING`, `LOW` + +### Volatile Variables + +Variables modified in interrupts must be declared `volatile`: +```cpp +volatile boolean needsWalk = false; +``` + +This tells the compiler the variable can change unexpectedly, preventing optimization issues. + +### State Management + +The sketch tracks system state to coordinate multiple components: +- Current traffic light position +- Crosswalk request status +- Timing for different sequences + +## Timing Adjustments + +Adjust these variables to change behavior: + +```cpp +int traffic_timer = 5000; // 5 second traffic lights +int walk_timer = 3000; // 3 second walk signal +``` + +## Challenges & Extensions + +1. **Realistic timing**: Make green light longer than yellow +2. **Yellow before green**: Add yellow light when transitioning from red to green +3. **Multiple crosswalks**: Add crosswalk signals for perpendicular traffic +4. **Sound effects**: Add piezo buzzer for walk signal +5. **Debouncing**: Prevent multiple button presses during same cycle +6. **Display countdown**: Add 7-segment display showing time remaining + +## Example Extension: Different Light Durations + +```cpp +void loop() { + currentTrafficLight = cycleTrafficLight(currentTrafficLight); + + int currentTimer; + // Green light is longer + if(currentTrafficLight == GREEN_TRAFFIC) { + currentTimer = 5000; + // Yellow is shorter + } else if(currentTrafficLight == YELLOW_TRAFFIC) { + currentTimer = 1500; + } else { + currentTimer = 3000; + } + + if(currentTrafficLight == RED_TRAFFIC && needsWalk) { + crosswalk(); + } else { + delay(currentTimer); + } +} +``` + +## Troubleshooting + +**Button doesn't work:** +- Check interrupt is on pin 2 +- Verify pull-down resistor +- Try changing CHANGE to RISING in attachInterrupt() + +**Crosswalk activates at wrong time:** +- Check logic in loop() - should only trigger when RED +- Verify needsWalk is being reset in crosswalk() + +**Lights stay on:** +- Ensure previous light is turned off in cycleTrafficLight() +- Check LED connections + +**Unpredictable behavior:** +- Confirm needsWalk is declared volatile +- Check for loose connections + +## Learning Outcomes + +After completing this project, you should understand: +- How to use hardware interrupts for responsive input +- Why volatile variables are needed with interrupts +- State management in embedded systems +- Creating complex timing sequences +- Coordinating multiple outputs with conditional logic + +## Author + +Joshua Shanks + +## License + +Original work - free to use and modify