Build a Bluetooth Heart Rate Chart

Use Claude Code to stream Bluetooth heart rate data into a live local chart.

Introduction

30 Second Summary

A fitness band may measure your pulse all day, yet its live readings often stay inside the companion app. That makes the journey from sensor signal to moving chart feel hidden.

In this project, you will use Claude Code to build a local, read-only viewer that turns your own band's standard Bluetooth Low Energy signal into a live heart rate chart. The viewer is for wellness learning only, so it never diagnoses, screens, reassures, or guides treatment.

What You'll Build

You will switch on your band's heart rate broadcast, watch live readings stream through one terminal, and see those readings move across a chart in another.

By the end of this project, you'll have:

  • A broadcast-aware scanner that shows No Heart Rate Service devices found. while broadcast is off, then identifies your band after you enable its standard Heart Rate Service signal.
  • A tested packet decoder that turns specification-derived bytes into Heart rate: 72 bpm and RR interval: 1.000 s.
  • A live local viewer that streams Heart rate: N bpm, records each reading in heart_rate.csv, and refreshes a moving chart in a second terminal.
  • Secret Mission: Add a second chart panel for RR intervals that handles bands that do not broadcast them.

Are there any prerequisites?

You'll need eligible Claude Code access, internet access, a supported computer with Bluetooth, your own compatible fitness band, and its official companion app or manual.

Use this chart for wellness learning only. Never use it to decide that a heart problem is absent.

Before We Start

This opening checkpoint keeps every later decision focused on a local, read-only general-wellness chart that uses only your own heart rate band. The chart must never diagnose, screen, reassure, or guide treatment for a heart problem.

Set Up Claude Code and Python

Your machine needs Claude Code plus a Python project environment before it can run the Bluetooth scripts.

A virtual environment keeps this project's packages separate from the rest of your computer. That isolation makes the later scripts easier to run and troubleshoot.

Bleak provides Bluetooth Low Energy access. Matplotlib draws the live chart.

In this step, get ready to:
  • Install and authenticate Claude Code. Its readiness prompt returns the exact confirmation.
  • Install Python 3.13 or later. Its version check succeeds.
  • Create the heart-rate-chart folder with an active .venv. Bleak 3.1.0 and Matplotlib 3.11.2 are verified.
Connect Claude Code to your account

Claude Code runs from Terminal on macOS or Command Prompt on Windows. Its first interactive session guides you through authentication.

The sign-in flow uses the eligible account you already prepared, so you are not creating another project resource.

  • Press Cmd+Space on macOS or the Windows key on Windows to open system search.
  • Type Terminal on macOS or Command Prompt on Windows.
  • Press Enter to open the terminal app.
  • Install Claude Code and start its first session by running your platform's commands below:

macOS

curl -fsSL https://claude.ai/install.sh | bash
claude --version
claude

What does this command do?

  • The first line downloads and runs the official Claude Code installer.
  • The second line prints the installed Claude Code version.
  • The final line starts the interactive session.

Windows

curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
claude --version
claude

What does this command do?

  • The first line downloads the official Windows installer. It runs the installer before removing the downloaded installer file.
  • The second line prints the installed Claude Code version.
  • The final line starts the interactive session.

You should see a version number followed by (Claude Code). The interactive session then presents the sign-in flow.

  • Complete the sign-in flow with your eligible Claude Code account.

You should arrive at the Claude Code prompt after authentication.

  • Confirm the session is ready by pasting this exact prompt:
Reply with exactly this sentence and do not create any files: Claude Code is ready for the heart rate project.

What does this prompt do?

This prompt checks that Claude Code can receive instructions. It also prevents the setup check from creating project files.

You should see exactly Claude Code is ready for the heart rate project. That response proves your authenticated session is working.

Claude Code did not start?

  • Close the terminal app after installation. Open it again before rerunning the version check.
  • Confirm that you completed the official sign-in flow with an eligible account.
  • Check your internet connection before running the installer again.

Still stuck? Help me troubleshoot my Claude Code installation or sign-in flow.

Prepare the Python runtime

The scripts in this project require Python 3.13 or later. The current download provides CPython 3.15.2.

  • Return to the terminal prompt using Claude Code's on-screen exit guidance.
  • Open the Python downloads page in your browser.

macOS

  • Install Python 3.15.2 with the signed macOS installer and its standard options.
  • Select Python 3.15.2 on the downloads page.
  • Download the signed macOS installer.
  • Run the installer with its standard options.
  • Run Install Certificates.command from the installed Python folder.
  • Find the installed Python folder in Applications.
  • Open Install Certificates.command inside that folder.

You should see the certificate installation complete in a terminal window.

Windows

  • Install the Python install manager from the downloads page.
  • Choose the Windows installer from the downloads page.
  • Run the downloaded installer with its standard options.
  • Install the Python 3.15 runtime by running:
py install 3.15

What does this command do?

The Python install manager downloads and installs the PythonCore 3.15 runtime. The py launcher then provides access to it from Command Prompt.

You should see the Python 3.15 runtime finish installing.

  • Check the installed Python version by running your platform's command below:

macOS

python3 --version

What does this command do?

The command asks the installed Python interpreter to print its version. It does not create or change any files.

Windows

py --version

What does this command do?

The Python launcher prints the version of its current runtime. It does not create or change any files.

You should see Python 3.13 or later. Python 3.15.2 is expected from the current download.

✔️ I see version 3.13 or higher

Python meets the project's minimum version. You can build the isolated environment next.

ⓧ I see an older version

The terminal is still finding an older Python installation.

  • Run the signed Python 3.15.2 installer again on macOS.
  • Run the Python install manager again on Windows.
  • Close the terminal app after installation.
  • Open the terminal app again.
  • Rerun your platform's version check.

ⓧ Command not found

The terminal cannot find the new Python installation.

  • Rerun the signed installer from the Python downloads page on macOS.
  • Reinstall the Python install manager from the downloads page on Windows.
  • Close the terminal app after installation.
  • Open the terminal app again.
  • Rerun your platform's version check.

That version check confirms Python is ready for the packages used in this project.

  • Start Claude Code from the same terminal by running:
claude

What does this command do?

The command starts a new Claude Code session from your current terminal. You will use it to confirm the Python version without creating files.

  • Ask Claude Code to confirm the Python version by pasting the prompt for your platform:

macOS

Do not create files. Run the Python version command for my platform and tell me only whether it is Python 3.13 or later. I am using Mac.

What does this prompt do?

Claude Code runs the macOS version check. Its response focuses only on whether Python meets the minimum version.

Windows

Do not create files. Run the Python version command for my platform and tell me only whether it is Python 3.13 or later. I am using Windows 11.

What does this prompt do?

Claude Code runs the Windows version check. Its response focuses only on whether Python meets the minimum version.

Claude Code should confirm that your Python version is 3.13 or later.

Build the isolated project environment

The project folder gives every later script one predictable home. The virtual environment keeps the pinned package versions inside that folder.

  • Return to the terminal prompt using Claude Code's on-screen exit guidance.
  • Move to your Desktop by running the command for your platform:

macOS

cd ~/Desktop

What does this command do?

The cd command changes the terminal's current location to your Desktop.

Windows

cd /d "%USERPROFILE%\Desktop"

What does this command do?

The command changes Command Prompt to the current user's Desktop folder. The drive changes too when the Desktop is on another drive.

  • Create the heart-rate-chart folder and enter it by running:

macOS

mkdir heart-rate-chart
cd heart-rate-chart

What does this command do?

The first line creates the project folder on your Desktop. The second line makes it the terminal's current location.

Windows

mkdir heart-rate-chart
cd heart-rate-chart

What does this command do?

The first line creates the project folder on your Desktop. The second line makes it the current Command Prompt location.

You should see the terminal prompt move inside the heart-rate-chart folder.

  • Create and activate the .venv virtual environment by running your platform's commands:

macOS

python3 -m venv .venv
source .venv/bin/activate

What does this command do?

  • The first line creates an isolated Python environment inside .venv.
  • The second line activates that environment for the current terminal session.

Windows

py -m venv .venv
.venv\Scripts\activate

What does this command do?

  • The first line creates an isolated Python environment inside .venv.
  • The second line activates that environment for the current Command Prompt session.

You should see (.venv) at the beginning of the prompt. That prefix confirms the isolated environment is active.

  • Install Bleak 3.1.0 and Matplotlib 3.11.2 by running your platform's command:

macOS

python3 -m pip install 'bleak==3.1.0' 'matplotlib==3.11.2'

What does this command do?

The command uses the active Python environment's package installer. It pins both libraries to the versions used throughout this project.

  • Bleak provides the cross-platform Bluetooth Low Energy scanner and client.
  • Matplotlib provides the live chart window and animation tools.

Windows

py -m pip install "bleak==3.1.0" "matplotlib==3.11.2"

What does this command do?

The command uses the active Python environment's package installer. It pins both libraries to the versions used throughout this project.

  • Bleak provides the cross-platform Bluetooth Low Energy scanner and client.
  • Matplotlib provides the live chart window and animation tools.

The first download can take a little longer while Python retrieves the packages. You should see the installation finish without an error.

  • Start Claude Code inside the active heart-rate-chart environment by running:
claude

What does this command do?

Claude Code starts from the project folder with the virtual environment active. This gives it access to the Python installation and packages you just prepared.

Before you send the final check, do you expect Python and both pinned packages to pass from the same active environment?

  • Allow only the local version checks if Claude Code asks for permission.
  • Verify the active Python environment by pasting this exact prompt:
Do not create any scripts yet. Run checks that print the active Python version and the installed distribution versions for bleak and matplotlib. Confirm only whether Python is 3.13 or later, bleak is 3.1.0, and matplotlib is 3.11.2.

What does this prompt do?

Claude Code reads the active interpreter version plus the installed package metadata. The prompt explicitly keeps project scripts out of this setup step.

You should see three successful confirmations. They cover Python 3.13 or later plus Bleak 3.1.0 and Matplotlib 3.11.2.

Your terminal history now includes the Claude Code version from installation. It also includes the final Python and package checks.

That is the setup complete. Your isolated workspace is ready without any project scripts being created yet.

Your tools are installed and your package versions are locked in. Next up, you will build a read-only scanner and prove that the band stays hidden while heart rate broadcast is off.

Prove the Band Is Hidden

Your isolated Python workspace is ready. You can now use Claude Code to build a scanner with Bleak.

A band that is not broadcasting the Bluetooth Low Energy Heart Rate Service should be invisible to a service-filtered scan.

In this step, get ready to:
  • Create scan.py as a read-only scanner for Heart Rate Service 180D.
  • Keep heart rate broadcast off on your own band. Its standard heart rate service remains hidden.
  • Run scan.py. Its intentional first scan prints No Heart Rate Service devices found..
Create the read-only scanner

Bluetooth Low Energy devices advertise small packets that scanners can observe without connecting. The service_uuids filter limits the results to devices advertising 180D.

Why use the standard service?

The standard Heart Rate Service gives compatible bands a shared GATT contract. Filtering for its service UUID keeps the scanner useful across compatible devices.

The script only observes advertisements. It avoids connections, pairing, reads, writes, and private protocols.

  • Start Claude Code inside the active heart-rate-chart folder by running this command:
claude

What does this command do?

The command starts an interactive Claude Code session in your current heart-rate-chart folder. Claude Code can create scan.py there while the virtual environment remains active.

  • Give Claude Code the scanner requirements by pasting this prompt:
Create a Python script named scan.py. Use asyncio and BleakScanner only. Scan for 10 seconds with BleakScanner.discover, set return_adv=True, and filter only for standard Heart Rate Service UUID 180D. Print each matching device's local name, address or macOS UUID, and advertised service UUIDs. If there are no matches, print exactly: No Heart Rate Service devices found. The script must only scan. It must not connect, pair, read, write, or use any private UUID. Do not rename the file. After writing it, summarize the safety boundary in one sentence.

What does this prompt build?

  • The BleakScanner.discover call performs one 10-second scan.
  • The return_adv=True setting includes each device's advertisement data.
  • The service filter keeps only advertisements for 180D.
  • The safety rules prevent the script from connecting to a device or changing it.

Claude Code creates scan.py with the filtered 10-second scan.

You now have your first project file. Its read-only boundary keeps this experiment focused on public advertisements.

✔️ Awesome, I've got everything!

Your scan.py is ready when it matches the requested read-only behavior.

ⓧ I'd like to double check the full code

Compare your complete scan.py with this reference line by line.

import asyncio

from bleak import BleakScanner

HEART_RATE_SERVICE_UUID = "180D"


async def main() -> None:
    results = await BleakScanner.discover(
        timeout=10.0,
        return_adv=True,
        service_uuids=[HEART_RATE_SERVICE_UUID],
    )

    if not results:
        print("No Heart Rate Service devices found.")
        return

    for device, advertisement in results.values():
        name = advertisement.local_name or device.name or "Unknown"
        services = ", ".join(advertisement.service_uuids) or "none"
        print(f"{name} | {device.address} | services: {services}")


if __name__ == "__main__":
    asyncio.run(main())
Run the intentional empty scan

This test holds the band's broadcast state at off. The controlled condition reveals whether ordinary Bluetooth availability exposes the Heart Rate Service.

  • Set heart rate broadcast to off in your band's official companion app.
  • Return to the official companion app for your own band.
  • Open the settings page for your band.
  • Use your band's manual to locate the heart rate broadcast control if the label differs.

Your band's heart rate broadcast control should now show that broadcasting is off.

  • Ask Claude Code to audit the scanner by pasting this prompt:
Do not modify scan.py. Check that it only scans for service 180D and then give me the single run command for my platform. Tell me that finding no matching band is expected on this first run.

What does this prompt check?

Claude Code checks the scanner's safety boundary before giving you the platform command. This preserves the controlled test without changing scan.py.

  • Exit the Claude Code session by pressing Ctrl+C until your project shell returns.

Your terminal returns to the heart-rate-chart folder. The prompt should still begin with (.venv).

Before you run the scanner, what exact line do you expect it to print?

  • Run the audited scanner with the command for your platform:

macOS

python3 scan.py

Windows

py scan.py

What does this command do?

The command uses the active virtual environment's Python interpreter to execute scan.py. The script listens for Heart Rate Service advertisements for 10 seconds.

The terminal prints exactly No Heart Rate Service devices found..

You have proved the hidden state. Your scanner cannot discover the standard service while heart rate broadcast is off.

Scanner stopped before the expected message?

Your terminal may need permission to use Bluetooth.

  • On macOS, open System Settings.
  • Select Privacy & Security.
  • Select Bluetooth.
  • Allow Terminal to use Bluetooth.

Still stuck? Help me diagnose why scan.py stops before printing its empty-scan result.

Your scanner now proves the band stays hidden while heart rate broadcast is off. Next, you will change the device setting that exposes the standard service.

Turn On Heart Rate Broadcast

Your read-only Bluetooth Low Energy scanner produced the expected empty result while broadcast was off. That result proved the filter for standard service 180D is working.

Ordinary Bluetooth availability leaves Heart Rate Service 180D hidden from the read-only scanner.

The companion app controls what your band advertises. The existing scan.py remains unchanged throughout this step.

In this step, get ready to:
  • Enable standard Heart Rate Service broadcast on only your own band. Its companion app shows the control set to On.
  • Run scan.py again. It displays your own band with advertised service 180D.
  • Capture your own band's address or macOS UUID for the live reader.
Enable broadcast on your own band

Heart rate broadcast makes your band advertise standard service 180D to nearby scanners. Finding this setting can be fiddly because each companion app places it differently.

  • Set Heart Rate Broadcast or HR Broadcast to On for only your own band.
  • In the official companion app, select only the band you own.
  • Open Device settings or Device Settings.
  • Find Heart Rate Broadcast or HR Broadcast.

You should see the broadcast control set to On in the companion app.

  • Keep the operating system's Bluetooth pairing settings closed.
  • Keep every device you do not own unselected.
  • Return to your authenticated Claude Code session from earlier.
  • Ask Claude Code to confirm the safety boundary by pasting this prompt:
Do not write or change code. Reply in three short bullets that this project uses only my own device, does not pair through operating-system Bluetooth settings, and never writes to a Bluetooth characteristic.

What does this prompt do?

  • The prompt asks Claude Code to restate the ownership boundary.
  • It confirms that operating-system pairing stays outside the project.
  • It confirms that the project never writes to a Bluetooth characteristic.

Claude Code replies with three short bullets covering your own device, no operating-system pairing, and no characteristic writes.

Scan for your own band and save its identifier

The scanner still filters advertisements for standard service 180D. This keeps the results focused without connecting to any device.

Before you ask Claude Code to run the scan, do you expect the result to match the empty first scan?

  • Run the read-only scan through Claude Code by pasting this prompt:
Do not modify scan.py. Run it now. If one or more service 180D devices appear, tell me to copy the address or macOS UUID for only the device I own. Do not connect to any device.

What does this prompt do?

  • Claude Code checks the existing scan.py without modifying it.
  • It runs the scanner while preserving the read-only boundary.
  • It limits the identifier you capture to the device you own.

Claude Code runs the matching command for your platform inside the active virtual environment.

macOS

python3 scan.py

Windows

py scan.py

What does this command do?

The platform's Python launcher runs the existing scan.py file. The script scans for advertisements containing service 180D.

The scan lasts 10 seconds, so the quiet pause is part of the check. You should then see your own band's name with its address or macOS UUID.

The same result should list advertised service UUIDs that include 180D.

Still seeing an empty scan?

  • Move your own band closer to the computer.
  • Confirm that you are wearing the band.
  • Switch its broadcast control off in the official companion app.
  • Switch its broadcast control back on.
  • Run the scan again.
  • Check the band's official manual if its menu labels differ from the common examples.

Still stuck? Help me troubleshoot why my own heart rate band is not appearing in a read-only scan for service 180D.

  • Copy the address or macOS UUID shown for only your own band here: your own device identifier.

You now have the identifier needed to target your own band in a later step.

  • Confirm that scan.py stayed unchanged with the check below.

✔️ Awesome, I've got everything!

Good. Your scanner stayed read-only while the band's broadcast setting changed.

ⓧ I'd like to double check the full code

Compare your unchanged scan.py with this complete reference.

import asyncio

from bleak import BleakScanner

HEART_RATE_SERVICE_UUID = "180D"


async def main() -> None:
    results = await BleakScanner.discover(
        timeout=10.0,
        return_adv=True,
        service_uuids=[HEART_RATE_SERVICE_UUID],
    )

    if not results:
        print("No Heart Rate Service devices found.")
        return

    for device, advertisement in results.values():
        name = advertisement.local_name or device.name or "Unknown"
        services = ", ".join(advertisement.service_uuids) or "none"
        print(f"{name} | {device.address} | services: {services}")


if __name__ == "__main__":
    asyncio.run(main())

That is the signal path unlocked. Next, you will decode a standard heart rate packet before using live notifications.

Decode a Heart Rate Packet

Your second scan proved that your own band exposes the standard Heart Rate Service. Now you can turn its compact measurement packets into values a person can read.

A discovered sensor still needs a decoder that translates its flags and little-endian fields into a human-readable heart rate before live Bluetooth data is involved.

In this step, get ready to:
  • Create decode_hr.py. Its parser handles standard flags, heart rate values, optional Energy Expended data, and RR intervals.
  • Run the specification-derived example. Its output shows Heart rate: 72 bpm followed by RR interval: 1.000 s.
Build the packet decoder

A Heart Rate Measurement packet begins with a flags byte. That byte tells the decoder which fields follow.

How do the flags shape the packet?

  • Bit 0 selects an 8-bit or 16-bit heart rate value.
  • Bit 3 signals an optional Energy Expended field.
  • Bit 4 signals optional RR intervals measured in units of 1/1024 second.
  • Little-endian fields place the least significant byte first.
  • Ask Claude Code to create the decoder by pasting this exact prompt:
Create decode_hr.py. Add a function named parse_heart_rate that accepts bytes, validates the packet length, reads the flags byte, supports both uint8 and little-endian uint16 heart rate values, skips the optional little-endian Energy Expended field when flag bit 3 is set, and returns every optional little-endian RR interval in seconds when flag bit 4 is set. In the main block, decode bytes.fromhex("16 48 00 04"). Print the heart rate using exactly this format: Heart rate: N bpm. Then print the first RR interval to three decimal places. This byte sequence is worked from the Bluetooth specification and was not captured from a real band. Do not add device-specific logic.

What does this prompt do?

  • The parse_heart_rate function validates packet lengths before reading each field.
  • The flags determine the heart rate width and the location of optional fields.
  • The worked example proves the parser with specification-derived bytes instead of data captured from a band.
  • The device-independent design keeps the decoder reusable for any compatible standard notification.

You should see Claude Code create decode_hr.py with parse_heart_rate and the specification-derived example. That gives your project a reusable decoder without adding device-specific logic.

✔️ Awesome, I've got everything!

Your decode_hr.py now contains the parser and the specification-derived example.

ⓧ I'd like to double check the full code

The complete decode_hr.py is shown below for line-by-line comparison.

def parse_heart_rate(data: bytes) -> tuple[int, list[float]]:
    if len(data) < 2:
        raise ValueError("Heart Rate Measurement needs flags and a value")

    flags = data[0]
    index = 1

    if flags & 0x01:
        if len(data) < index + 2:
            raise ValueError("Missing uint16 heart rate value")
        heart_rate = int.from_bytes(data[index : index + 2], "little")
        index += 2
    else:
        heart_rate = data[index]
        index += 1

    if flags & 0x08:
        if len(data) < index + 2:
            raise ValueError("Missing Energy Expended field")
        index += 2

    rr_intervals: list[float] = []
    if flags & 0x10:
        if (len(data) - index) % 2 != 0:
            raise ValueError("RR-Interval field has an incomplete value")
        while index < len(data):
            raw_rr = int.from_bytes(data[index : index + 2], "little")
            rr_intervals.append(raw_rr / 1024.0)
            index += 2

    return heart_rate, rr_intervals


if __name__ == "__main__":
    example = bytes.fromhex("16 48 00 04")
    bpm, rr_values = parse_heart_rate(example)
    print(f"Heart rate: {bpm} bpm")
    print(f"RR interval: {rr_values[0]:.3f} s")
Run the specification-derived example

The bytes 16 48 00 04 come from the standard packet format. They contain no information captured from your band.

Before Claude Code runs the example, do you expect the packet to contain an RR interval?

  • Ask Claude Code to run and verify the decoder by pasting this exact prompt:
Do not change decode_hr.py. Run it and verify that the exact first line is Heart rate: 72 bpm and that the next line reports 1.000 seconds. If either value differs, inspect the flag bits and little-endian byte order, fix only the decoder, and run it again.

What does this prompt do?

  • Claude Code runs decode_hr.py without changing a correct decoder.
  • The output check confirms that the flags and little-endian fields were interpreted correctly.
  • Any repair stays inside the decoder so the specification-derived example remains unchanged.

You should see Heart rate: 72 bpm as the first line. The next line reports RR interval: 1.000 s.

Before you run the script yourself, do you expect the terminal output to match Claude Code's check?

  • Run decode_hr.py directly with the command for your platform:

macOS

python3 decode_hr.py

Windows

py decode_hr.py

What does this command do?

The command starts Python inside your active virtual environment. Python executes the main block in decode_hr.py and prints the decoded values.

The first output line is exactly Heart rate: 72 bpm. The line RR interval: 1.000 s follows it.

You have now proved that your decoder can turn a standard byte packet into readable heart rate and timing values.

Seeing different values?

  • Compare the handling of bit 0, bit 3, and bit 4 with the Heart Rate Measurement format.
  • Check that int.from_bytes uses little-endian byte order.
  • Confirm the worked example still uses bytes.fromhex("16 48 00 04").

Still stuck? Help me debug my Heart Rate Measurement byte parser.

Your decoder now turns standard packet bytes into readable measurements. Next up, you will use it to process live notifications from your own band.

Stream and Chart Live Heart Rate

Your decoder now turns a specification-derived packet into a heart rate and an RR interval. The next goal is to collect those readings from your own band while a live chart displays them.

Your decoded sample is static until a CSV handoff feeds a separate Matplotlib chart from the live Bluetooth stream.

In this step, get ready to:
  • Create read_hr.py with Claude Code. It subscribes only to 2A37. It logs each reading to heart_rate.csv.
  • Create live_chart.py. It charts the latest 60 valid heart rates from the CSV file.
  • Run the reader and chart in separate terminals. The reader prints repeated heart rates while the chart updates with the latest bpm.
Create the live reader

The standard Heart Rate Measurement characteristic is 2A37. Its GATT notifications carry the bytes that your existing parse_heart_rate() function understands.

  • Create read_hr.py in the existing heart-rate-chart folder by pasting this exact prompt into the Claude Code session from earlier:
Create read_hr.py. Import parse_heart_rate from decode_hr.py. Accept my copied device address or macOS UUID as one required command-line argument. Use BleakScanner.find_device_by_address to obtain a BLEDevice, connect with BleakClient without pairing, and subscribe only to standard Heart Rate Measurement characteristic UUID 2A37 with start_notify. For each notification, append timestamp, heart_rate, and the first rr_interval_seconds value or a blank to heart_rate.csv. Create the CSV header if needed. Print every reading using exactly: Heart rate: N bpm. Keep listening until I press Ctrl+C. The script must never call a GATT write method, use 2A39, pair, or inspect private UUIDs. After writing the file, audit it against those restrictions.

What does this prompt do?

  • The generated ensure_csv() function creates the CSV header when the data file is missing or empty.
  • The handle_notification() function decodes each packet. It appends the timestamp and parsed values to the CSV file.
  • The stream() function finds only the identifier you provide. It subscribes only to 2A37.

You should see Claude Code create read_hr.py and report that it never pairs or writes to a characteristic. Good progress. The read-only collection half of your pipeline is ready.

✔️ Awesome, I've got everything!

Your read_hr.py file is ready for the live test.

ⓧ I'd like to double check the full code

Here is the complete read_hr.py file for reference.

import argparse
import asyncio
import csv
from datetime import datetime
from pathlib import Path

from bleak import BleakClient, BleakScanner

from decode_hr import parse_heart_rate

HEART_RATE_MEASUREMENT_UUID = "2A37"
CSV_PATH = Path("heart_rate.csv")


def ensure_csv() -> None:
    if not CSV_PATH.exists() or CSV_PATH.stat().st_size == 0:
        with CSV_PATH.open("w", newline="", encoding="utf-8") as csv_file:
            writer = csv.writer(csv_file)
            writer.writerow(["timestamp", "heart_rate", "rr_interval_seconds"])


def handle_notification(_characteristic: object, data: bytearray) -> None:
    try:
        heart_rate, rr_intervals = parse_heart_rate(bytes(data))
    except ValueError as error:
        print(f"Skipped malformed notification: {error}")
        return

    timestamp = datetime.now().isoformat(timespec="seconds")
    first_rr = f"{rr_intervals[0]:.6f}" if rr_intervals else ""

    with CSV_PATH.open("a", newline="", encoding="utf-8") as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow([timestamp, heart_rate, first_rr])

    print(f"Heart rate: {heart_rate} bpm")


async def stream(device_identifier: str) -> None:
    ensure_csv()
    device = await BleakScanner.find_device_by_address(
        device_identifier,
        timeout=20.0,
    )
    if device is None:
        raise RuntimeError("Could not find your device. Confirm broadcast is on.")

    async with BleakClient(device) as client:
        await client.start_notify(
            HEART_RATE_MEASUREMENT_UUID,
            handle_notification,
        )
        print("Streaming heart rate. Press Ctrl+C to stop.")
        while True:
            await asyncio.sleep(1.0)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("device_identifier")
    arguments = parser.parse_args()

    try:
        asyncio.run(stream(arguments.device_identifier))
    except KeyboardInterrupt:
        print("Stopped heart rate stream.")


if __name__ == "__main__":
    main()
Create the separate chart reader

The chart owns the graphical event loop while the reader owns the Bluetooth connection. Passing readings through heart_rate.csv keeps those two long-running processes independent.

  • Create live_chart.py in the existing heart-rate-chart folder by pasting this exact prompt into Claude Code:
Create live_chart.py. It must not import bleak or use Bluetooth. Read heart_rate.csv once per second, keep the latest 60 valid heart_rate values, and update one Matplotlib line with matplotlib.animation.FuncAnimation. Store the FuncAnimation object in a variable that lives until the window closes. Show the latest bpm in the chart title. If the CSV does not exist or has no valid rows, keep the window open with a waiting title. Do not rename the file.

What does this prompt do?

  • The generated read_heart_rates() function skips invalid CSV rows. It keeps only the latest 60 valid readings.
  • The update() function replaces the line data. It updates the title with the latest bpm.
  • The stored animation variable keeps FuncAnimation alive while the chart window remains open.

You should see Claude Code create live_chart.py and confirm that the file reads only from heart_rate.csv. The chart process contains no Bluetooth access or threads.

✔️ Awesome, I've got everything!

Your live_chart.py file is ready to display the collected readings.

ⓧ I'd like to double check the full code

Here is the complete live_chart.py file for reference.

import csv
from pathlib import Path

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

CSV_PATH = Path("heart_rate.csv")
MAX_POINTS = 60


def read_heart_rates() -> tuple[list[int], list[int]]:
    if not CSV_PATH.exists():
        return [], []

    heart_rates: list[int] = []
    with CSV_PATH.open("r", newline="", encoding="utf-8") as csv_file:
        for row in csv.DictReader(csv_file):
            try:
                heart_rates.append(int(row["heart_rate"]))
            except (KeyError, TypeError, ValueError):
                continue

    heart_rates = heart_rates[-MAX_POINTS:]
    return list(range(len(heart_rates))), heart_rates


figure, axis = plt.subplots()
line, = axis.plot([], [], color="crimson", linewidth=2)
axis.set_title("Live Heart Rate: waiting for heart_rate.csv")


def update(_frame: object) -> tuple[object]:
    sample_numbers, heart_rates = read_heart_rates()

    if not heart_rates:
        line.set_data([], [])
        axis.set_title("Live Heart Rate: waiting for heart_rate.csv")
        return (line,)

    line.set_data(sample_numbers, heart_rates)
    axis.relim()
    axis.autoscale_view()
    axis.set_title(f"Live Heart Rate: {heart_rates[-1]} bpm")
    return (line,)


animation = FuncAnimation(
    figure,
    update,
    interval=1000,
    cache_frame_data=False,
)
plt.show()
Run the reader and chart

Each script runs continuously. Separate terminals let the reader wait for notifications while the chart keeps its graphical event loop responsive.

  • Audit the final files without changing them by pasting this exact prompt into Claude Code:
Audit the final files without changing them. Confirm that read_hr.py writes heart_rate.csv and that live_chart.py only reads it. Confirm that no thread is used, no Bluetooth write is used, and the two scripts are meant to run in separate terminals. Reply with the two file names and one sentence per file.

What does this prompt do?

The audit checks the boundary between collection and visualization. It also confirms that the final scripts contain no write operation or thread.

You should see one sentence for read_hr.py and one sentence for live_chart.py. The first writes the CSV file. The second only reads it.

  • End the Claude Code session so Terminal 1 returns to its normal command prompt.
  • Create a second window from the Terminal or Command Prompt app you already have open.
  • Store your copied band address or macOS UUID in this project value: PASTE-YOUR-DEVICE-IDENTIFIER-HERE.

Finding the band can take up to 20 seconds, so a short pause from Bleak is expected.

Before you start the reader, do you expect one printed sample or a continuing stream?

  • Start the reader in Terminal 1 by running the commands for your platform:

macOS

source .venv/bin/activate
python3 read_hr.py "[[DEVICE_IDENTIFIER="PASTE-YOUR-DEVICE-IDENTIFIER-HERE"]]"

Windows

.venv\Scripts\activate
py read_hr.py "[[DEVICE_IDENTIFIER="PASTE-YOUR-DEVICE-IDENTIFIER-HERE"]]"

What do these commands do?

  • The first command activates the existing .venv environment in Terminal 1.
  • The second command starts read_hr.py with your own band's identifier.
  • The reader stays active until you press Ctrl+C.

You should see Streaming heart rate. Press Ctrl+C to stop. followed by repeated Heart rate: N bpm lines. That is the collection half working: heart_rate.csv is growing with new rows.

  • Start the chart in Terminal 2 by running the commands for your platform:

macOS

cd heart-rate-chart
source .venv/bin/activate
python3 live_chart.py

Windows

cd heart-rate-chart
.venv\Scripts\activate
py live_chart.py

What do these commands do?

  • The first command moves Terminal 2 into the existing heart-rate-chart folder.
  • The second command activates the same virtual environment used by the reader.
  • The final command starts the CSV-only chart process.

You should see a responsive chart window whose title changes to the latest bpm. You now have the full pipeline running from your own band's notifications to a local chart.

Rows in heart_rate.csv can contain blank RR interval values. Heart rate collection still succeeds because RR intervals are optional.

Reader or chart not updating?

  • Confirm Terminal 1 is printing heart rate lines before checking the chart.
  • Confirm heart_rate.csv is gaining rows in the heart-rate-chart folder.
  • Confirm Terminal 2 is using the same folder and virtual environment as Terminal 1.

Still stuck? Help me debug why my live heart rate reader or chart is not updating.

Secret mission

Add an RR-Interval Panel

Extend your live chart with a second panel for RR intervals from the same CSV data. The panel will plot available values or show a clear no-data state when your band does not broadcast them.

Clean Up Your Resources

Clean Up Your Resources

Everything you created lives inside the local heart-rate-chart folder, which creates no project-specific cloud charges. Your existing Claude Code access may still use subscription or Console billing.

Decide whether to keep your resources running, pause them to come back later, or delete them entirely.

Resources you used:

  • The local heart-rate-chart folder.
  • The local .venv virtual environment containing Bleak and Matplotlib.
  • The local scripts scan.py, decode_hr.py, read_hr.py, and live_chart.py.
  • The local data file heart_rate.csv.
  • The standard Heart Rate Service 180D broadcast enabled on your own band.

Keep everything running

No action is needed. Choose this if you want to keep using your live heart rate viewer.

  • Keep the heart-rate-chart folder on your computer.
  • Retain heart_rate.csv for another local wellness visualization session.
  • Leave heart rate broadcast switched on only while you are actively using the viewer.

Pause - I'll come back to this later

Shut down the live processes to free both terminals. Your scripts and recorded readings remain available for another session.

  • Switch back to the terminal running read_hr.py if it is still active.
  • Press Ctrl+C to stop the heart rate stream.
  • Close the live chart window.
  • Switch off heart rate broadcast in your band's companion app.
  • Keep the heart-rate-chart folder for your next session.

Delete - I don't want to use this again

Remove the local project and start fresh. Deleting the folder permanently erases its scripts and recorded wellness data.

  • Copy heart_rate.csv outside heart-rate-chart if you want to keep the recorded readings.
  • Switch back to the terminal running read_hr.py if it is still active.
  • Press Ctrl+C to stop the heart rate stream.
  • Close the live chart window.
  • Switch off heart rate broadcast in your band's companion app.

The deletion commands target only the local heart-rate-chart folder. Use the tab for your computer.

macOS

  • In the Terminal currently inside heart-rate-chart, delete the project folder by running these commands:
cd ..
rm -rf heart-rate-chart
What do these commands do?

The first command moves Terminal to the folder that contains heart-rate-chart.

The second command removes the project folder. Every file inside it is removed too.

After the commands finish, heart-rate-chart no longer exists on your Mac.

Windows

  • In the Command Prompt currently inside heart-rate-chart, delete the project folder by running these commands:
cd ..
rmdir /s /q heart-rate-chart
What do these commands do?

The first command moves Command Prompt to the folder that contains heart-rate-chart.

The second command removes the project folder. Every file inside it is removed too.

After the commands finish, heart-rate-chart no longer exists on your Windows computer.

Nice Work!

Nice Work!

You did it! You built a read-only viewer that turns your own band's standard Bluetooth Low Energy heart rate notifications into a live chart.

You've learned how to:

  • Proved the broadcast boundary with scan.py. It found no Heart Rate Service device while broadcast was off. It then found your own band on service 180D after broadcast was enabled.
  • Decoded the specification-derived bytes 16 48 00 04 with byte parsing. The result showed Heart rate: 72 bpm. It also reported RR interval: 1.000 s.
  • Built a two-process CSV pipeline. read_hr.py logs live 2A37 notifications without pairing or GATT writes. live_chart.py keeps the latest 60 readings moving in a responsive Matplotlib chart. The finished viewer stays within general wellness use.
  • Secret Mission: Added a shared-x second chart panel to live_chart.py. It plots RR intervals when they are available. Otherwise, it shows RR intervals: not broadcast by this device.

Ready to quiz yourself?