# Arduino Height Measurement System

# 

## 1. Project Overview

The Arduino-based Height Measurement System uses an ultrasonic sensor to measure the distance between the sensor and a person's head.

The sensor is mounted at a fixed height, facing downward. When a person stands beneath it, the system measures the distance from the sensor to the person's head.

Python calculates the person's height using the following formula:

**Person's Height = Sensor Mounting Height − Measured Distance**

### Technologies Used

- Arduino UNO
- HC-SR04 Ultrasonic Sensor
- Arduino IDE
- Python
- Flask
- PySerial
- HTML, CSS and JavaScript

### System Architecture

```text
       HC-SR04 Sensor
              |
              v
          Arduino UNO
              |
              v
     USB Serial Communication
              |
              v
       Python Flask Server
              |
              v
       Height Calculation
              |
              v
        Web Dashboard
              |
              v
       Display Height (cm)
```

---

## 2. Hardware Requirements

| Component | Quantity |
|---|---:|
| Arduino UNO | 1 |
| HC-SR04 Ultrasonic Sensor | 1 |
| Jumper Wires | 4 |
| USB Cable | 1 |
| Computer/Laptop | 1 |
| Fixed mounting frame | 1 |

## 3. Hardware Connections

### HC-SR04 to Arduino UNO

| HC-SR04 Pin | Arduino UNO |
|---|---|
| VCC | 5V |
| GND | GND |
| TRIG | Digital Pin 9 |
| ECHO | Digital Pin 10 |

**Sensor Installation:**

- Mount the ultrasonic sensor horizontally at a fixed height.
- The sensor must face vertically downward.
- Keep the sensor stable.
- The person should stand directly below the sensor.
- Measure the distance from the sensor's ultrasonic face to the floor.

For example:

```text
       HC-SR04 SENSOR
       (Fixed Position)
       ┌─────────────┐
       │             │
       └─────────────┘
              |
              |
              |  Measured Distance
              |
           _______
          /       \
         |  HEAD   |
         |         |
         | PERSON  |
         |         |
         |         |
         |         |
         |_________|

       ----------------
             FLOOR
```

**Example:**

- Sensor mounting height = 200 cm
- Distance from sensor to head = 30 cm

Person's height:

\[
H=200-30
\]

\[
\boxed{H=170\text{ cm}}
\]

*Important: The sensor mounting height must be measured accurately from the sensor's measuring face to the floor.*

---

## 4. Arduino IDE Setup

### Step 1: Install Arduino IDE

Download Arduino IDE:

https://www.arduino.cc/en/software

Install and open Arduino IDE.

### Step 2: Arduino Code

The following program measures the distance using the HC-SR04 sensor and sends the measurement to Python through serial communication.

No additional Arduino library is required.

```cpp
// HC-SR04 Configuration

#define TRIG_PIN 9
#define ECHO_PIN 10

void setup() {

    // Start serial communication
    Serial.begin(9600);

    // Configure sensor pins
    pinMode(TRIG_PIN, OUTPUT);
    pinMode(ECHO_PIN, INPUT);
}

void loop() {

    // Send ultrasonic trigger pulse
    digitalWrite(TRIG_PIN, LOW);
    delayMicroseconds(2);

    digitalWrite(TRIG_PIN, HIGH);
    delayMicroseconds(10);

    digitalWrite(TRIG_PIN, LOW);

    // Read echo duration
    long duration = pulseIn(ECHO_PIN, HIGH, 30000);

    if (duration == 0) {

        Serial.println("ERROR");

    }
    else {

        // Calculate distance in centimeters
        float distance = duration * 0.0343 / 2;

        // Send distance to Python
        Serial.println(distance);
    }

    delay(500);
}
```

### Step 3: Upload the Program

1. Connect Arduino UNO to your computer.
2. Select the correct board: Arduino UNO.
3. Select the correct COM port.
4. Upload the program.
5. Check the Serial Monitor at 9600 baud.

Expected output:

```text
30.20
30.10
30.25
30.15
```

These values represent the measured distance between the sensor and the person's head.

---

## 5. Python Environment Setup

### Step 1: Install Python

Download Python:

https://www.python.org/downloads/

Verify installation:

```bash
python --version
```

### Step 2: Create Project Folder

Open PowerShell or Command Prompt.

```powershell
mkdir Height_Measurement
cd Height_Measurement
```

### Step 3: Create Python Virtual Environment

```bash
python -m venv venv
```

### Step 4: Activate Virtual Environment

**Windows PowerShell:**

```powershell
.\venv\Scripts\Activate.ps1
```

If PowerShell blocks activation:

```powershell
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
```

Then activate again:

```powershell
.\venv\Scripts\Activate.ps1
```

**Windows Command Prompt:**

```cmd
venv\Scripts\activate.bat
```

After activation, you should see:

```text
(venv) C:\...\Height_Measurement>
```

### Step 5: Install Required Libraries

```bash
pip install flask pyserial
```

Save dependencies:

```bash
pip freeze > requirements.txt
```

---

## 6. Project Structure

```text
Height_Measurement/
│
├── venv/
│
├── app.py
│
└── requirements.txt
```

The complete website, including HTML, CSS and JavaScript, will be included inside `app.py`.

---

## 7. Create the Python Application

Create a file named `app.py`.

**Important:** Set `SENSOR_HEIGHT_CM` according to the actual height of your mounted sensor.

For this example, the sensor is mounted 200 cm above the floor.

```python
from flask import Flask, jsonify, render_template_string
import serial
import threading
import time

app = Flask(__name__)

# ==================================
# CONFIGURATION
# ==================================

SERIAL_PORT = "COM3"
BAUD_RATE = 9600

# Sensor height from floor in centimeters
SENSOR_HEIGHT_CM = 200

# Measurement variables
distance = 0
person_height = 0

connection_status = "Disconnected"
last_updated = "--"


# ==================================
# ARDUINO SERIAL COMMUNICATION
# ==================================

def read_arduino():

    global distance, person_height
    global connection_status, last_updated

    while True:

        try:

            print("Connecting to Arduino...")

            arduino = serial.Serial(
                SERIAL_PORT,
                BAUD_RATE,
                timeout=2
            )

            time.sleep(2)

            connection_status = "Connected"

            print("Arduino Connected!")

            while True:

                line = arduino.readline().decode(
                    "utf-8",
                    errors="ignore"
                ).strip()

                if not line or line == "ERROR":
                    continue

                try:

                    measured_distance = float(line)

                    # Validate sensor measurement
                    if not 2 <= measured_distance < SENSOR_HEIGHT_CM:
                        continue

                    # Calculate person's height
                    calculated_height = (
                        SENSOR_HEIGHT_CM - measured_distance
                    )

                    distance = round(measured_distance, 2)

                    person_height = round(
                        calculated_height, 2
                    )

                    last_updated = time.strftime("%H:%M:%S")

                    print(
                        f"Distance: {distance} cm | "
                        f"Height: {person_height} cm"
                    )

                except ValueError:
                    continue

        except Exception as error:

            connection_status = "Disconnected"

            print("Arduino Error:", error)

            time.sleep(3)


# ==================================
# WEB DASHBOARD
# ==================================

HTML_PAGE = """

<!DOCTYPE html>
<html>

<head>

    <title>Height Measurement System</title>

    <meta name="viewport"
          content="width=device-width, initial-scale=1">

    <style>

        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #eef2f7;
            color: #172554;
        }

        header {
            background: #172554;
            color: white;
            text-align: center;
            padding: 30px 15px;
        }

        header h1 {
            margin: 0 0 10px;
        }

        .container {
            max-width: 900px;
            margin: 50px auto;
            padding: 15px;
        }

        .cards {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            gap: 25px;
        }

        .card {
            background: white;
            width: 300px;
            padding: 35px 20px;
            border-radius: 18px;
            text-align: center;
            box-shadow: 0 5px 20px #0001;
        }

        .icon {
            font-size: 45px;
        }

        .value {
            font-size: 45px;
            font-weight: bold;
            margin: 20px 0;
        }

        .height {
            color: #2563eb;
        }

        .distance {
            color: #ea580c;
        }

        .status-box {
            background: white;
            padding: 22px;
            border-radius: 15px;
            margin-top: 30px;
            text-align: center;
        }

        .connected {
            color: #16a34a;
        }

        .disconnected {
            color: #dc2626;
        }

        .info {
            background: white;
            padding: 20px;
            margin-top: 25px;
            border-radius: 15px;
            text-align: center;
        }

        footer {
            text-align: center;
            padding: 25px;
            color: #64748b;
        }

    </style>

</head>

<body>

    <header>

        <h1>📏 Height Measurement System</h1>

        <p>Arduino-Based Smart Height Monitoring</p>

    </header>


    <div class="container">

        <div class="cards">

            <div class="card">

                <div class="icon">🧍</div>

                <h2>Person's Height</h2>

                <div class="value height" id="height">

                    -- cm

                </div>

                <p>Calculated Height</p>

            </div>


            <div class="card">

                <div class="icon">📡</div>

                <h2>Sensor Distance</h2>

                <div class="value distance" id="distance">

                    -- cm

                </div>

                <p>Distance from Sensor to Head</p>

            </div>

        </div>


        <div class="info">

            <h3>Sensor Mounting Height</h3>

            <h2 id="mounting">-- cm</h2>

        </div>


        <div class="status-box">

            <h3>

                Arduino Status:

                <span id="status" class="disconnected">

                    Checking...

                </span>

            </h3>

            <p>

                Last Updated:

                <span id="updated">--</span>

            </p>

        </div>

    </div>


    <footer>

        Arduino UNO + HC-SR04 | Python Flask

    </footer>


    <script>

        async function updateData() {

            try {

                const response = await fetch("/data");

                const data = await response.json();


                document.getElementById("height").innerText =
                    data.height + " cm";


                document.getElementById("distance").innerText =
                    data.distance + " cm";


                document.getElementById("mounting").innerText =
                    data.mounting_height + " cm";


                const status =
                    document.getElementById("status");


                status.innerText = data.status;


                status.className =
                    data.status === "Connected"
                    ? "connected"
                    : "disconnected";


                document.getElementById("updated").innerText =
                    data.updated;

            }

            catch (error) {

                document.getElementById("status").innerText =
                    "Connection Error";

            }

        }


        updateData();

        // Refresh dashboard every second
        setInterval(updateData, 1000);

    </script>

</body>

</html>

"""


# ==================================
# FLASK ROUTES
# ==================================

@app.route("/")
def home():

    return render_template_string(HTML_PAGE)


@app.route("/data")
def get_data():

    return jsonify({

        "height": person_height,

        "distance": distance,

        "mounting_height": SENSOR_HEIGHT_CM,

        "status": connection_status,

        "updated": last_updated

    })


# ==================================
# START APPLICATION
# ==================================

if __name__ == "__main__":

    thread = threading.Thread(
        target=read_arduino,
        daemon=True
    )

    thread.start()


