Differences

This shows you the differences between two versions of the page.

Link to this comparison view

pm:prj2026:bianca.popa1106:ana.stanciulescu [2026/05/06 16:36]
ana.stanciulescu
pm:prj2026:bianca.popa1106:ana.stanciulescu [2026/05/25 01:42] (current)
ana.stanciulescu
Line 24: Line 24:
 **Component List**: **Component List**:
  
-^ Component ​     ^ Role in the project ​      ^  +^ Component ​     ^ Role in the project ​      ^ Datasheet ​  
-| ATmega328P-XMINI ​   | System brain; processes signals and controls peripherals ​    | +| ATmega328P-XMINI ​   | System brain; processes signals and controls peripherals ​    | [[https://​www.pdf.support/​pdfviewer?​url=https%3A%2F%2Fpdf.support%2F709a4da2%2Fmicrochip.com%2FATMEGA328P-XMINI.pdf|ATmega328P-XMINI]] ​  
-| 3× HC-SR04 ​   | Distance measurement using ultrasonic waves (Left, Center, Right) ​ | +| 3× HC-SR04 ​   | Distance measurement using ultrasonic waves (Left, Center, Right)  ​| [[https://​www.alldatasheet.com/​datasheet-pdf/​pdf/​2216428/​MULTICOMP/​HC-SR04.html|HC-SR04]] ​
-| 3× RGB LEDs (CC)    | Optical indicator for each sensor (Green = Safe, Red = Stop) | +| 3× RGB LEDs (CC)    | Optical indicator for each sensor (Green = Safe, Red = Stop) |  ​
-3x Resistor ​  | A separate 220Ω resistor was used in series with the anode of each RGB LED | +6x Resistor ​  | A separate 220Ω resistor was used in series with the anode of each RGB LED |  ​
-| Passive Buzzer ​  | Variable sound alarm   | +| Passive Buzzer ​  | Variable sound alarm   | [[https://​www.alldatasheet.com/​datasheet-pdf/​pdf/​1284499/​JOY-IT/​KY-006.html|Buzzer]] ​
-| LCD 16×2  | Displays measured distances ​  |+| LCD 16×2  | Displays measured distances ​  | [[https://​www.datasheetcafe.com/​JHD162A-pdf-14977/​|LCD 16×2]] ​|
  
 **Electrical Diagram**: **Electrical Diagram**:
Line 47: Line 47:
  
 ===== Software Design ===== ===== Software Design =====
 +
 +==== Architectural Overview ====
 +
 +The firmware is built around a non-blocking main loop that coordinates four main tasks: collecting distance data from three ultrasonic sensors, controlling three RGB LEDs for visual feedback, driving a passive piezo buzzer for audio alerts, and updating a 16×2 I²C LCD display.
 +
 +To keep the system responsive, sensor measurements are handled asynchronously using interrupts, so the CPU never sits idle waiting for an echo pulse. The buzzer also runs on its own timing scheduler based on millis(), which means the beep pattern remains smooth and independent from the sensor update rate.
  
 The program logic is based on calculating the round-trip time of the sound signal:​$$Distance = \frac{Time \times Speed of Sound}{2}$$ The program logic is based on calculating the round-trip time of the sound signal:​$$Distance = \frac{Time \times Speed of Sound}{2}$$
-**Algorithm structure**:​ 
  
-  ​- Initialization:​ Configure I/O pins, timers for PWM (buzzer/LED), and LCD interface.+The firmware is split into five logical modules: 
 +  - **HC-SR04 Driver (Interrupt-Based)** 
 +    - Each ultrasonic sensor is represented by a structure containing pointers to its TRIG and ECHO registers along with the associated bit positions. 
 +    - Sending the trigger pulse is straightforward:​ a synchronous 10 µs pulse is applied to the TRIG pin. The actual echo timing, however, is handled entirely through Pin Change Interrupts (PCINTs), allowing the CPU to continue running other tasks while the sensor responds. 
 +    - Because the three ECHO pins are connected to different ports (PD4, PB0, and PC1), they use separate interrupt vectors. 
 +    - Each ISR records the timestamp from micros() when the echo signal rises, then calculates the pulse duration when the signal falls. Once the measurement is complete, a volatile bool ready flag is set so the main loop knows fresh data is available. 
 +  - **Exponential Moving Average Filter** 
 +    - Raw HC-SR04 measurements naturally fluctuate by about ±1–2 cm because of acoustic noise, reflections,​ and air movement. To stabilize the readings, each sensor output is filtered using a first-order Exponential Moving Average (EMA): y[n]=αx[n]+(1−α)y[n−1]. 
 +    - The smoothing factor was chosen experimentally as: α=0.5 
 +    - This value provided a good balance between responsiveness and stability. In practice, the system reacts to genuine distance changes within roughly 500 ms while ignoring most isolated spikes and noisy readings. 
 +  - **LED State Machine with Asymmetric Hysteresis** 
 +    - Each RGB LED behaves as a simple three-state machine: Green — safe distance; Yellow — caution; Red — critical proximity. 
 +    - The state transitions are based on the filtered sensor distance. Moving toward a more urgent state happens immediately once a threshold is crossed, while returning to a safer state requires the distance to exceed the threshold by an additional 1 cm margin. 
 +    - The LEDs are driven using digitalWrite() on the red and green channels. PWM-based color blending was tested early in development,​ but later removed because of timer conflicts with the buzzer subsystem. 
 +  - **Adaptive Buzzer Driver** 
 +    - The buzzer always reacts to the minimum distance detected across all three sensors, since even one nearby obstacle should trigger an alert. 
 +    - That minimum distance controls two things simultaneously:​ Beep period — interpolated from 600 ms at 30 cm down to 80 ms at 10 cm; Tone frequency — interpolated from 1500 Hz to 2048 Hz. The higher frequency corresponds to the buzzer module’s resonant frequency, which produces the loudest output according to the datasheet. 
 +    - Once the measured distance drops below 10 cm, the buzzer switches to a continuous 2048 Hz tone. 
 +    - The actual waveform generation is handled by Arduino’s tone() function, which configures Timer2 in CTC mode and toggles the buzzer pin (A0) inside the TIMER2_COMPA_vect ISR. The higher-level beep scheduling uses millis(), keeping the implementation fully non-blocking. 
 +  - **LCD Driver** 
 +    - The LCD updates every 100 ms and displays the filtered distances in a compact two-line layout: L:<​dist>​cm C:<​dist>​cm\nR:<​dist>​cm Min:<​dist>​ 
 +    - Each value is formatted as a fixed-width,​ right-aligned field so changing numbers overwrite cleanly without leaving visual artifacts. If a reading is invalid or out of range, the display shows ---. 
 + 
 + 
 +**Algorithm structure**:​ 
 +  ​- Initialization:​ Configure I/O pins, timers for the buzzer ​and sensors, and LCD interface.
   - Main loop:   - Main loop:
     - Sequentially trigger Sensor 1, then 2, then 3 (to avoid interference).     - Sequentially trigger Sensor 1, then 2, then 3 (to avoid interference).
     - Calculate distance for each sensor.     - Calculate distance for each sensor.
-    - Update LED states ​(e.g., below 10 cm → Red).+    - Update LED states.
     - Compute buzzer “beep” frequency based on the smallest detected distance.     - Compute buzzer “beep” frequency based on the smallest detected distance.
     - Update LCD display.     - Update LCD display.
 +
 +===== Design Decision and Trade-Offs =====
 +
 +==== PCINT vs. Polling for Echo Measurement ====
 +
 +The first version of the project measured echo duration using a busy-wait loop around TCNT1. While functional, this approach blocked the CPU and tied up Timer1 completely.
 +
 +Moving to Pin Change Interrupts solved both issues: the CPU remains free while measurements occur in the background, and Timer1 is now available for future extensions.
 +
 +==== Digital LEDs vs. PWM Color Blending ====
 +
 +An earlier implementation used PWM to create smooth color transitions between green, yellow, and red. In practice, this introduced visible glitches because the LEDs relied on timers shared with the buzzer subsystem.
 +
 +Specifically,​ Timer2 is also used by tone(), so activating the buzzer interfered with PWM outputs on pins such as D3 and D11.
 +
 +The final design uses three discrete LED states with hysteresis. Although this sacrifices continuous color gradients, it results in clearer feedback and avoids timer conflicts entirely.
 +
 +==== Sequential Sensor Triggering ====
 +
 +Triggering all three ultrasonic sensors simultaneously would reduce measurement time, but it risks acoustic cross-talk, where one sensor receives another sensor’s echo.
 +
 +To avoid this, the sensors are triggered sequentially with a 10 ms delay between measurements,​ ensuring each sensor only processes its own reflected pulse.
  
 ===== Results ===== ===== Results =====
  
-The system ​achieves an accuracy of approximately 12 cm. The interface is intuitive, ​allowing ​the driver ​to quickly ​identify which part of the car is closest to an obstacle.+The completed ​system ​was mounted on a toy car and powered by a portable USB 
 +power bank, making it fully self-contained and independent of a development 
 +computer. 
 + 
 +The three ultrasonic sensors achieve a ranging ​accuracy of approximately 
 +1-2 cm across their effective operating range. The exponential moving average 
 +filter applied to each sensor'​s readings eliminates the characteristic 
 ++/-1-2 cm jitter of the raw HC-SR04 output, producing stable distance values 
 +without introducing perceptible lag (the system reacts to a real distance 
 +change in under ~600 ms). 
 + 
 +The three-zone feedback proved ​intuitive: each RGB LED independently reflects 
 +the proximity state of its corresponding sensor (green / yellow / red), 
 +letting ​the driver ​instantly ​identify which side of the vehicle ​is closest to 
 +an obstacle. ​The buzzer, driven by the minimum of the three measured 
 +distances, varies both its beep cadence and its tone frequency continuously 
 +as the nearest obstacle approaches, culminating in a continuous tone below 
 +10 cm. The LCD provides a precise numeric readout of all three distances 
 +simultaneously,​ for drivers who prefer a "​dashboard"​ view. 
 + 
 +The asymmetric hysteresis on the LED state machine eliminated the boundary 
 +flickering observed in early prototypes, and the non-blocking architecture 
 +keeps the buzzer responsive even while the sensors are being polled. 
 + 
 +A demonstration of the complete system in operation:​ 
 + 
 +[[https://​youtube.com/​shorts/​_dmrASQBtu4|Watch here]]
  
 ===== Conclusions ===== ===== Conclusions =====
  
-The implementation ​on the ATmega328P ​demonstrates efficient handling of multiple sensors simultaneously using interrupts ​and timers. The project ​is scalable ​and can be integrated into any small vehicle.+Building this project taught me a lot about how embedded systems work in 
 +practice - not just coding, but also designing the hardware, debugging odd 
 +issues, and getting everything to run smoothly ​on a moving toy car. 
 + 
 +One of the biggest lessons was learning how limited hardware resources have 
 +to be shared carefully. The ATmega328P ​only has three timers, ​and I needed 
 +them for the buzzer, LEDs, and time measurements at the same time. I ran 
 +into conflicts where the LEDs flickered whenever the buzzer was active, which 
 +forced me to better understand how the timers ​and pins are connected. In the 
 +end, I simplified the LEDs to basic on/off colors to avoid those conflicts. 
 + 
 +I also learned how important pin selection is. At one point I connected a 
 +sensor to PB5, not realizing it was also used by the programmer. That caused 
 +upload failures until I rewired the sensor, and after that I became much more 
 +careful about checking pin functions beforehand. 
 + 
 +Another challenge was dealing with noisy sensor readings. The measured 
 +distance constantly shifted by small amounts, which made the LEDs flicker and 
 +the buzzer react unpredictably. Adding a simple averaging filter and some 
 +hysteresis made the whole system feel much more stable and reliable. 
 + 
 +Writing the I2C LCD driver and interrupt handlers from scratch also gave me a 
 +much better understanding of what happens behind the scenes, compared to just 
 +using ready-made libraries. 
 + 
 +If I continued developing the project, I would add a low-power sleep mode, 
 +improve the LED fading effects, ​and possibly include more sensors for better 
 +coverage around the car. 
 + 
 +Overall, the project showed that the ATmega328P ​can reliably handle multiple 
 +sensors and peripherals at once using timers and interrupts, while the 
 +modular structure makes the system easy to adapt for other small vehicles.
pm/prj2026/bianca.popa1106/ana.stanciulescu.1778074617.txt.gz · Last modified: 2026/05/06 16:36 by ana.stanciulescu
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0