Read Car Telemetry with Claude Code
Build a simulated OBD-II dashboard, CSV logger, and chart with Claude Code.
Introduction
30 Second Summary
A car can feel like a black box when useful engine data stays hidden. Testing new software on a real vehicle adds safety pressure before you can focus on learning.
In this project, you will use Claude Code to build a read-only Python reader for simulated OBD-II data. The finished workflow shows live engine values before preserving a short drive as a CSV log, a chart, and a cautious written explanation.
What You'll Build
Your finished terminal demo streams six engine readings from a simulated car before saving the drive as a chart and a cautious written explanation.
By the end of this project, you'll have:
- A live read-only dashboard where six simulated engine readings refresh in your terminal. You will see coolant temperature, voltage, RPM, speed, short-term fuel trim, and long-term fuel trim.
- A saved drive record that captures timestamped telemetry in drive_log.csv. You can also run a read-only diagnostic trouble code check that handles an empty result clearly.
- A two-panel chart that makes changes in speed and fuel trim easy to see. You will also have a data-grounded summary that separates observations from possible explanations.
- Secret Mission: Add a custom simulated P0420 fault to the simulator. Retrieve it safely before explaining what the code does and does not prove.
Are there any prerequisites?
You need a Mac running macOS 13 or later or a Windows 10/11 computer with internet access plus a payment method for Claude Pro. No Python or coding experience is required.
Before We Start
You are building a safe reader that shows six read-only simulated OBD-II values, logs a simulated drive, checks stored codes, charts the data, and explains the evidence. A local simulator comes first so you can learn the complete workflow without changing or diagnosing a real vehicle.
Set Up Claude Code and Python
The simulator keeps this project away from your car. Nothing can run until your computer has the right development tools.
You will use Claude Code to create project files from terminal prompts. Python will run the reader inside an isolated environment.
In this step, get ready to:
- Create a paid Claude Pro account.
- Install Claude Code and Python 3.14.10.
- Prepare the project with its pinned dependencies.
Create Claude access and install Claude Code
Claude Code requires a paid Claude Pro subscription for this project. The Free plan does not include Claude Code.
Know What Renews
Choosing Claude Pro starts a recurring subscription. The US monthly price is $20 before applicable tax.
The annual option costs $200 up front. That price is equivalent to $17 per month.
Claude Pro renews until canceled. The local simulator and Python packages create no additional usage charges.
- Visit the Claude pricing page.
- Create your Claude account.
- Choose Pro to start the paid subscription.
- Confirm that your account shows Claude Pro access.
Your paid account is now ready. Next, you will install the terminal tool that uses it.
Claude Code installs through a normal terminal session. Administrator access is not required.
macOS
- Press Cmd+Space to open Spotlight.
- Type Terminal into Spotlight.
- Press Enter to open macOS Terminal.
- Install Claude Code by running this command:
curl -fsSL https://claude.ai/install.sh | bash
What Does This Command Do?
This command downloads the official Claude Code installer. The script installs the command-line tool for your user account.
Windows
- Press the Windows key to open Start.
- Type Windows PowerShell into Start.
- Select Windows PowerShell from the results.
- Choose Open.
- Install Claude Code by running this command:
irm https://claude.ai/install.ps1 | iex
What Does This Command Do?
This command downloads the official Claude Code PowerShell installer. The script installs the command-line tool for your user account.
- Close the terminal window after the installer finishes.
- Return to your terminal using the same search steps.
- Check the Claude Code installation by running:
claude --version
What Should You See?
You should see a version followed by (Claude Code). This confirms that your terminal can find the installation.
- Start your first Claude Code session by running:
claude
What Happens Next?
Claude Code starts a browser authentication flow for your subscription. A successful sign-in returns you to the Claude Code prompt.
- Follow the browser sign-in flow with your new paid account.
- Return to the terminal after authentication succeeds.
- Leave Claude Code by entering:
/exit
What Does This Command Do?
This command closes the Claude Code session. You return to the normal terminal shell for the next installation.
Claude Code Not Starting?
Close every terminal window after installation. Reopen your terminal so it loads the updated command path.
Confirm that you completed browser authentication with the paid Claude account.
Ask for help with your exact installation result: Help me troubleshoot my Claude Code installation
Install Python 3.14.10
The project pins Python 3.14.10 because the emulator documents support for the Python 3.14 release line. A version check tells you which installation path to use.
macOS
- Check for the required Python runtime by running:
python3.14 --version
How To Read the Result
A successful check prints the installed Python version. A missing command means the runtime still needs to be installed.
Windows
- Check for the required Python runtime by running:
py -V:3.14 --version
How To Read the Result
A successful check prints the selected Python 3.14 runtime version. A missing command means the Python install manager still needs to be installed.
- Choose the tab that matches the version-check result.
✔️ I see version 3.14.10
Your computer already has the exact runtime for this project. Python is ready for the project environment.
ⓧ I see an older version
The installed runtime is older than the project pin. Install the current Python 3.14.10 maintenance release before continuing.
macOS
- Visit the Python 3.14.10 release page.
- Select the macOS installer for macOS 10.15 or later.
- Open the downloaded .pkg file.
- Complete the installer with its default options.
The certificate helper is easy to miss because it sits inside the installed Python application folder.
- Open /Applications/Python 3.14/Install Certificates.command.
- Wait for the certificate process to finish.
You should see Successfully installed certifi followed by update complete.
- Verify the new runtime by running:
python3.14 --version
What Should You See?
The command should now print Python 3.14.10. This confirms that the required runtime is available.
Windows
- Visit the Python downloads page for Windows.
- Install the Python install manager from the page or Microsoft Store.
- Return to your normal Windows PowerShell session.
- Install the current Python 3.14 runtime by running:
py install 3.14
py -V:3.14 --version
What Do These Commands Do?
- The first command installs the current runtime from the Python 3.14 release line.
- The second command selects that runtime for the version check.
The final output should show Python 3.14.10.
ⓧ Command not found
The required Python launcher is not available yet. Install it through the official platform path below.
macOS
- Visit the Python 3.14.10 release page.
- Select the macOS installer for macOS 10.15 or later.
- Open the downloaded .pkg file.
- Complete the installer with its default options.
The certificate helper is easy to miss because it sits inside the installed Python application folder.
- Open /Applications/Python 3.14/Install Certificates.command.
- Wait for the certificate process to finish.
You should see Successfully installed certifi followed by update complete.
- Verify the installation by running:
python3.14 --version
What Should You See?
The command should print Python 3.14.10. Your Mac can now create the project environment.
Windows
- Visit the Python downloads page for Windows.
- Install the Python install manager from the page or Microsoft Store.
- Return to your normal Windows PowerShell session.
- Install the Python 3.14 runtime by running:
py install 3.14
py -V:3.14 --version
What Do These Commands Do?
- The first command installs the current runtime from the Python 3.14 release line.
- The second command verifies the installed runtime.
The final output should show Python 3.14.10.
Python Version Still Incorrect?
Close your terminal after installation. Reopen it so the shell can find the new runtime.
On Windows, make sure the version check includes the -V:3.14 selector.
Ask for help with the version shown on your screen: Help me fix my Python version
Create the project environment
A virtual environment keeps this project's packages inside .venv. This prevents its pinned versions from changing other Python projects on your computer.
macOS
- Create the car-computer-reader folder in your home directory by running the commands below:
mkdir -p "$HOME/car-computer-reader"
cd "$HOME/car-computer-reader"
python3.14 -m venv .venv
source .venv/bin/activate
What Do These Commands Do?
- The first command creates the fixed project folder in your home directory.
- The second command moves the terminal into that folder.
- The third command creates .venv with Python 3.14.10.
- The final command activates the isolated environment.
Your prompt should now include (.venv).
Windows
- Create the car-computer-reader folder in your home directory by running the commands below:
New-Item -ItemType Directory -Force "$HOME\car-computer-reader" | Out-Null
Set-Location "$HOME\car-computer-reader"
py -V:3.14 -m venv .venv
.\.venv\Scripts\Activate.ps1
What Do These Commands Do?
- The first command creates the fixed project folder in your home directory.
- The second command moves PowerShell into that folder.
- The third command creates .venv with the selected Python runtime.
- The final command activates the isolated environment.
Your prompt should now include (.venv).
PowerShell Blocking Activation?
PowerShell can block the activation script through its current-user execution policy. Apply the Python-documented fix once by running:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
This changes the policy for your user account. Retry the .venv activation command afterward.
Ask for help if activation is still blocked: Help me activate my Windows virtual environment
Your isolated environment is active. Claude Code can now create the only project file needed in this step.
- Start Claude Code inside the car-computer-reader folder by running:
claude
Why Start Claude Code Here?
Claude Code uses the current folder as its project context. Starting it here keeps requirements.txt inside car-computer-reader.
- Ask Claude Code to create the pinned dependency file by pasting this prompt:
Create a file named requirements.txt with exactly these five lines and no other files:
obd==0.7.3
ELM327-emulator==4.0.0
matplotlib==3.11.2
pint==0.24.4
pyserial==3.5
What Does This Prompt Control?
The prompt limits Claude Code to one file. Exact pins make every installation use the same package versions.
- The python-OBD package provides the read-only car-data commands.
- ELM327-emulator provides the simulated car interface.
- Matplotlib creates the drive chart.
- Pint handles physical measurement values.
- pySerial supports the local socket connection.
- Approve Claude Code's request to create requirements.txt.
- Return to the normal terminal shell by entering:
/exit
What Does This Command Do?
This closes the Claude Code session without removing the generated file. Your active virtual environment remains available in the terminal.
The dependency installer may print many download lines. Continuing output means the installation is still progressing.
- Install the pinned packages by running the commands below:
python -m pip install -r requirements.txt
python -c "import elm, matplotlib, obd, serial; print('Project dependencies ready')"
What Do These Commands Prove?
- The first command installs every exact version from requirements.txt into .venv.
- The second command imports the four runtime modules.
- The success message proves that Python can load the installed dependencies.
Dependency Installation Failed?
Confirm that your terminal prompt includes (.venv) before rerunning the installation.
Check that requirements.txt contains exactly five package lines. An extra character can change a package name or version.
Ask for help with the visible installer output: Help me fix my pinned dependency installation
Use these tabs to compare your dependency file with the project target.
✔️ Awesome, I've got everything!
Great. Save requirements.txt with the five pinned package lines.
ⓧ I'd like to double check the full code
obd==0.7.3
ELM327-emulator==4.0.0
matplotlib==3.11.2
pint==0.24.4
pyserial==3.5
What Should Match?
Compare every package name with your file. Compare every version pin before continuing.
Before the final check, what do you expect each version command to confirm?
macOS
- Run the final setup checks with these commands:
claude --version
python3.14 --version
python -c "import elm, matplotlib, obd, serial; print('Project dependencies ready')"
What Should You See?
You should see a Claude Code version. The Python check should print Python 3.14.10.
The final line should be Project dependencies ready. That message confirms that the project environment can import its dependencies.
Windows
- Run the final setup checks with these commands:
claude --version
py -V:3.14 --version
python -c "import elm, matplotlib, obd, serial; print('Project dependencies ready')"
What Should You See?
You should see a Claude Code version. The Python check should print Python 3.14.10.
The final line should be Project dependencies ready. That message confirms that the project environment can import its dependencies.
That is the setup complete. Claude Code is authenticated while Python can load every pinned project package.
Your development environment is ready. Next, you will start the simulated car and prove that Python can read its RPM value.
Connect to the Simulated Car
That groundwork is complete. Your Python environment can now import every pinned dependency.
This step connects your reader to a simulated car through a local TCP socket. A single read-only RPM query gives you the first proof that the simulator and reader can communicate.
In this step, get ready to:
- Prepare a second terminal work area with the project environment active.
- Start ELM327-emulator on a loopback socket.
- Build a read-only RPM connection check with Claude Code.
Prepare two terminal work areas
The emulator must keep running while the reader connects. Two terminal work areas give each process its own prompt.
A new shell starts outside your virtual environment. The second work area must return to car-computer-reader before activating .venv.
macOS
- Keep the existing Terminal window open for the emulator.
- Press Cmd+N in Terminal to create a second window.
- Return the second window to car-computer-reader and activate .venv by running:
cd "$HOME/car-computer-reader"
source .venv/bin/activate
What do these commands do?
- The first command returns the new Terminal window to your car-computer-reader folder.
- The second command activates the isolated packages inside .venv.
Windows
- Keep the existing Windows PowerShell window open for the emulator.
- Press the Windows key to open Start.
- Type Windows PowerShell into the search field.
- Select Windows PowerShell.
- Select Open to create a second window.
- Return the second window to car-computer-reader and activate .venv by running:
Set-Location "$HOME\car-computer-reader"
.\.venv\Scripts\Activate.ps1
What do these commands do?
- The first command returns the new PowerShell window to your car-computer-reader folder.
- The second command activates the isolated packages inside .venv.
You should now see (.venv) at the start of the prompt in both terminal work areas.
Missing the environment name?
- Confirm that the new terminal is inside the car-computer-reader folder.
- Rerun the activation command for your platform.
Help me activate the existing virtual environment in my second terminal window.
Start the local car emulator
The emulator acts like an ELM327 adapter connected to a car. Its loopback address keeps the test traffic on your computer.
- Switch back to the first terminal work area.
- Start the built-in car scenario on port 35000 by running:
python -m elm -s car -n 35000
What does this command do?
- The python -m elm portion starts the installed emulator package.
- The -s car portion selects its built-in simulated car scenario.
- The -n 35000 portion serves the emulator on local TCP port 35000.
You should see a CMD> prompt when the emulator is ready for its own commands.
- Remove the simulator's response delay by entering this at the CMD> prompt:
delay 0
Why remove the delay?
The emulator normally pauses before responding to each request. The delay 0 command removes that pause so this local connection check finishes quickly.
The emulator now waits at CMD> while serving the loopback socket at socket://127.0.0.1:35000.
- Leave the first terminal running at the CMD> prompt.
Emulator prompt not appearing?
- Confirm that (.venv) appears at the start of the first terminal prompt.
- Check whether an older emulator process is already using port 35000.
- Return to the first terminal after stopping that older process.
Help me diagnose why ELM327-emulator is not reaching its command prompt.
Build the connection check
The reader uses python-OBD to open the simulator's socket. Its first contract is narrow: connect safely, request RPM, print the result, and close the connection.
- Switch back to the second terminal work area.
- Continue the latest Claude Code conversation for this project by running:
claude -c
Why continue the conversation?
The claude -c command resumes the most recent Claude Code conversation in this folder. Claude keeps the project context while you add connection_check.py.
- Create the read-only connection checker by pasting this prompt into Claude Code:
Create connection_check.py for this project. It must import obd, connect to socket://127.0.0.1:35000 with obd.OBD using baudrate=38400, fast=False, and timeout=1.0, stop with a clear message if is_connected() is false, query only obd.commands.RPM, reject a null response with is_null(), print the protocol name and RPM value, and always close the connection. Do not add any write, clear-code, actuator, or programming command.
What does this prompt protect?
- The prompt fixes the destination at socket://127.0.0.1:35000 so the reader connects only to the local simulator.
- The obd.commands.RPM query requests one read-only engine-speed value.
- The connection checks turn missing communication into clear messages.
- The final safety rule excludes code clearing and every write path.
- Review the proposed connection_check.py file.
- Approve the file creation when Claude Code requests permission.
- Return to the normal shell by entering:
/exit
What does this command do?
The /exit command closes the Claude Code session. Your second terminal stays inside car-computer-reader with .venv active.
The key file is in place. connection_check.py now holds the read-only RPM handshake.
- Check the generated file against the exact target using the tabs below.
✔️ Awesome, I've got everything!
Your connection_check.py file is ready for its first connection test.
ⓧ I'd like to double check the full code
Your complete connection_check.py file should match this reference exactly.
import obd
PORT = "socket://127.0.0.1:35000"
def main():
connection = obd.OBD(
PORT,
baudrate=38400,
fast=False,
timeout=1.0,
)
try:
if not connection.is_connected():
raise SystemExit(
"Could not connect. Confirm the emulator is running on port 35000."
)
response = connection.query(obd.commands.RPM)
if response.is_null():
raise SystemExit("Connected, but the simulator returned no RPM value.")
print(f"Connected: {connection.protocol_name()}")
print(f"Engine RPM: {response.value}")
finally:
connection.close()
if __name__ == "__main__":
main()
How is the file structured?
- The PORT value points to the emulator's loopback socket.
- The main() function opens the connection with the required settings.
- The RPM query rejects missing data before printing the protocol and reading.
- The finally block closes the connection after every outcome.
Before you run this, what do you think the reader will report after its first handshake with the simulator?
- Test the completed connection checker by running:
python connection_check.py
What should I see?
You should see Connected: ISO 15765-4 (CAN 11/500) on the first line. The next line starts with Engine RPM: and includes a numeric reading.
You get one successful RPM snapshot before the script ends. That frozen value is the intended limitation of this first reader.
Connection check not succeeding?
- Confirm that the first terminal still shows the emulator's CMD> prompt.
- Confirm that the second terminal starts with (.venv).
- Compare connection_check.py with the full-code reference above.
Help me debug the read-only simulator connection.
That's the first handshake complete: your reader can reach the simulated car and return RPM. Next, you'll turn that frozen snapshot into a refreshing six-sensor dashboard.
Build the Live Dashboard
Your Python connection check proved that the simulator can answer a read-only RPM query. One frozen value cannot show how simulated driving conditions change.
This step uses Claude Code to turn repeated OBD-II sensor queries into a terminal dashboard. You will watch six values refresh once per second without adding any command that changes vehicle state.
In this step, get ready to:
- Define a strict read-only sensor contract for the dashboard.
- Run the dashboard to watch six simulated car values refresh.
Give Claude a strict read-only sensor contract
A sensor allowlist keeps the dashboard focused on approved queries. The contract also requires clean handling for missing values and interrupted sessions.
- Continue the Claude Code conversation from your app terminal by running:
claude -c
What does this command do?
The command resumes the most recent Claude Code conversation in the current project directory. This gives Claude the context from your connection check.
Claude session not opening?
- Confirm that you are using the app terminal from the previous step.
- Confirm that the terminal still has access to Claude Code.
Help me reopen my Claude Code session.
- Ask Claude to create the read-only dashboard by pasting this prompt:
Create dashboard_logger.py as a runnable dashboard. Reuse socket://127.0.0.1:35000 and the same obd.OBD connection settings from connection_check.py. Query only these read-only commands: COOLANT_TEMP, CONTROL_MODULE_VOLTAGE, RPM, SPEED, SHORT_FUEL_TRIM_1, and LONG_FUEL_TRIM_1. Store each non-null response.value.magnitude as a float, show N/A for null responses, clear and redraw a labeled terminal view once per second, handle Ctrl+C cleanly, and always close the connection. Add an argparse subcommand named dashboard. Do not add any command that changes simulator or vehicle state.
What does this prompt require?
- The six-command allowlist limits the app to the dashboard sensors.
- The null check displays N/A when a sensor has no value.
- The one-second loop turns individual snapshots into a refreshing display.
- The cleanup requirement closes the connection when you stop the dashboard.
- Approve Claude's request to create dashboard_logger.py.
You will see Claude report that dashboard_logger.py has been created. The project now has a dedicated dashboard command.
Dashboard file not created?
- Confirm that you approved Claude's file creation request.
- Ask Claude to retry the same dashboard request if it reported a file-writing problem.
Help me create the dashboard file safely.
- Return to the normal shell by entering:
/exit
What happens when you exit?
This ends the current Claude Code session while keeping the generated file in your project. Your activated virtual environment remains available in the terminal.
✔️ Awesome, I've got everything!
Good progress. dashboard_logger.py now contains the read-only connection logic and refreshing dashboard.
ⓧ I'd like to double check the full code
- Compare your dashboard_logger.py file with this complete version.
import argparse
import time
import obd
PORT = "socket://127.0.0.1:35000"
SENSORS = (
("coolant_c", "Coolant temperature", obd.commands.COOLANT_TEMP, "degC"),
("control_module_v", "Control-module voltage", obd.commands.CONTROL_MODULE_VOLTAGE, "V"),
("rpm", "Engine speed", obd.commands.RPM, "rpm"),
("speed_kph", "Vehicle speed", obd.commands.SPEED, "km/h"),
("short_fuel_trim_pct", "Short-term fuel trim", obd.commands.SHORT_FUEL_TRIM_1, "%"),
("long_fuel_trim_pct", "Long-term fuel trim", obd.commands.LONG_FUEL_TRIM_1, "%"),
)
def connect():
connection = obd.OBD(PORT, baudrate=38400, fast=False, timeout=1.0)
if not connection.is_connected():
connection.close()
raise RuntimeError("Could not connect. Confirm the emulator is running on port 35000.")
return connection
def read_value(connection, command):
response = connection.query(command)
if response.is_null():
return None
return float(response.value.magnitude)
def take_snapshot(connection):
return {key: read_value(connection, command) for key, _label, command, _unit in SENSORS}
def format_value(value, unit):
if value is None:
return "N/A"
return f"{value:.2f} {unit}"
def run_dashboard():
connection = connect()
try:
while True:
values = take_snapshot(connection)
print("\033[2J\033[H", end="")
print("SIMULATED CAR DASHBOARD")
print("Read-only local data. Press Ctrl+C to stop.\n")
for key, label, _command, unit in SENSORS:
print(f"{label:<30} {format_value(values[key], unit):>16}")
time.sleep(1)
except KeyboardInterrupt:
print("\nDashboard stopped.")
finally:
connection.close()
def build_parser():
parser = argparse.ArgumentParser(description="Read simulated OBD-II data without changing vehicle state.")
subparsers = parser.add_subparsers(dest="mode", required=True)
subparsers.add_parser("dashboard", help="Show a refreshing terminal dashboard.")
return parser
def main():
args = build_parser().parse_args()
if args.mode == "dashboard":
run_dashboard()
if __name__ == "__main__":
main()
How does the dashboard work?
- The SENSORS tuple defines the six allowed queries and their display labels.
- The take_snapshot() function collects one value from every sensor.
- The run_dashboard() function redraws the terminal once per second.
- The finally block closes the connection after every exit path.
Run and observe the dashboard
Before you run it, which values do you expect to change as the simulated driving scenario advances?
- Start the refreshing dashboard by running:
python dashboard_logger.py dashboard
What should I see?
The terminal clears between snapshots under the SIMULATED CAR DASHBOARD heading.
- You should see a Coolant temperature value.
- You should see a Control-module voltage value.
- You should see an Engine speed value.
- You should see a Vehicle speed value.
- You should see a Short-term fuel trim value.
- You should see a Long-term fuel trim value.
The values refresh once per second. Speed, RPM, and fuel trims change as the built-in scenario advances.
Dashboard not refreshing?
- Confirm that the emulator terminal remains open at the CMD> prompt.
- Confirm that .venv remains active in the app terminal.
- Compare the PORT value with the simulator's loopback socket.
Help me troubleshoot my refreshing dashboard.
- Stop the dashboard by pressing Ctrl+C after several refreshes.
You will see Dashboard stopped. before the app closes its connection. Your six read-only values now update safely from the simulated car.
Your dashboard can now show the drive as it happens. Next, you will preserve this moving data as a simulated drive log.
Log a Drive and Read Codes
Your six-value dashboard now turns simulated OBD-II responses into a live view. The next goal is to preserve those readings after they leave the screen.
Each refresh replaces the previous values, so the dashboard cannot show a drive's history. Claude Code will add CSV logging. It will also add a separate read-only stored-code check.
In this step, get ready to:
- Extend the dashboard app with logging and code retrieval.
- Record a timestamped simulated drive in drive_log.csv.
- Confirm that the default simulator reports no stored diagnostic trouble codes.
Extend the app with logging and code retrieval
The logger needs to preserve every snapshot with a timestamp. The code checker needs a narrow read-only path that handles the simulator's Mode 03 response format.
- Continue the Claude Code conversation for this project by running this command:
claude -c
What does this command do?
The -c option continues the most recent Claude Code conversation in the current project. Claude can use the existing dashboard as the starting point for this update.
- Paste this prompt into Claude Code:
Extend dashboard_logger.py without removing dashboard mode. Add a log subcommand with --seconds and --output options. Once per second, write timestamp_utc, elapsed_seconds, coolant_c, control_module_v, rpm, speed_kph, short_fuel_trim_pct, and long_fuel_trim_pct to CSV. Add a dtc subcommand that queries only obd.commands.GET_DTC. Use response.value when python-OBD decodes codes. If that list is empty, add an emulator-only read fallback that examines each response message's data after byte 0x43 in two-byte pairs, decodes the P/C/B/U letter and four digits, and looks up descriptions from obd.codes.DTC. Ignore 00 00 padding. Never query CLEAR_DTC and never send a write command.
What will Claude add?
- The run_log() function records one timestamped sensor snapshot per second.
- The decode_emulator_messages() function handles the simulator's Mode 03 payload when the normal decoder returns an empty value.
- The run_dtc_check() function queries only GET_DTC.
- The parser gains separate log and dtc modes.
- Approve the updated dashboard_logger.py file.
- Type /exit to return to the normal shell.
Does Claude propose a different safety boundary?
The finished app should contain sensor queries plus GET_DTC only. It should contain no code-clearing or write path.
Ask Claude to correct any drift before approving the file. Help me compare Claude's changes with the required read-only contract.
✔️ Awesome, I've got everything!
Your dashboard now supports live viewing, CSV logging, and read-only stored-code retrieval.
- Confirm that dashboard_logger.py is saved.
ⓧ I'd like to double check the full code
- Compare your dashboard_logger.py file with this complete reference:
import argparse
import csv
import time
from datetime import datetime, timezone
from pathlib import Path
import obd
from obd.codes import DTC
PORT = "socket://127.0.0.1:35000"
SENSORS = (
("coolant_c", "Coolant temperature", obd.commands.COOLANT_TEMP, "degC"),
("control_module_v", "Control-module voltage", obd.commands.CONTROL_MODULE_VOLTAGE, "V"),
("rpm", "Engine speed", obd.commands.RPM, "rpm"),
("speed_kph", "Vehicle speed", obd.commands.SPEED, "km/h"),
("short_fuel_trim_pct", "Short-term fuel trim", obd.commands.SHORT_FUEL_TRIM_1, "%"),
("long_fuel_trim_pct", "Long-term fuel trim", obd.commands.LONG_FUEL_TRIM_1, "%"),
)
def connect():
connection = obd.OBD(PORT, baudrate=38400, fast=False, timeout=1.0)
if not connection.is_connected():
connection.close()
raise RuntimeError("Could not connect. Confirm the emulator is running on port 35000.")
return connection
def read_value(connection, command):
response = connection.query(command)
if response.is_null():
return None
return float(response.value.magnitude)
def take_snapshot(connection):
return {key: read_value(connection, command) for key, _label, command, _unit in SENSORS}
def format_value(value, unit):
if value is None:
return "N/A"
return f"{value:.2f} {unit}"
def run_dashboard():
connection = connect()
try:
while True:
values = take_snapshot(connection)
print("\033[2J\033[H", end="")
print("SIMULATED CAR DASHBOARD")
print("Read-only local data. Press Ctrl+C to stop.\n")
for key, label, _command, unit in SENSORS:
print(f"{label:<30} {format_value(values[key], unit):>16}")
time.sleep(1)
except KeyboardInterrupt:
print("\nDashboard stopped.")
finally:
connection.close()
def run_log(seconds, output_name):
if seconds < 2:
raise ValueError("Log duration must be at least 2 seconds.")
output_path = Path(output_name)
fieldnames = ["timestamp_utc", "elapsed_seconds"] + [key for key, _label, _command, _unit in SENSORS]
connection = connect()
started = time.monotonic()
rows_written = 0
try:
with output_path.open("w", newline="", encoding="utf-8") as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
while time.monotonic() - started < seconds:
sample_started = time.monotonic()
row = {"timestamp_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"), "elapsed_seconds": round(sample_started - started, 2)}
row.update(take_snapshot(connection))
writer.writerow(row)
csv_file.flush()
rows_written += 1
print(f"Logged sample {rows_written} at {row['elapsed_seconds']:.2f} seconds")
sleep_for = 1 - (time.monotonic() - sample_started)
if sleep_for > 0:
time.sleep(sleep_for)
finally:
connection.close()
print(f"Wrote {rows_written} samples to {output_path}")
def decode_emulator_messages(messages):
decoded = []
seen = set()
groups = "PCBU"
for message in messages:
data = list(message.data)
if not data or data[0] != 0x43:
continue
payload = data[1:]
for index in range(0, len(payload) - 1, 2):
first = payload[index]
second = payload[index + 1]
if first == 0 and second == 0:
continue
code = f"{groups[first >> 6]}{(first >> 4) & 0x03}{first & 0x0F:X}{second:02X}"
if code not in seen:
decoded.append((code, DTC.get(code, "Description unavailable")))
seen.add(code)
return decoded
def read_stored_codes(connection):
response = connection.query(obd.commands.GET_DTC)
if response.value:
return response.value
return decode_emulator_messages(response.messages)
def run_dtc_check():
connection = connect()
try:
codes = read_stored_codes(connection)
finally:
connection.close()
if not codes:
print("No stored diagnostic trouble codes.")
return
print("Stored diagnostic trouble codes:")
for code, description in codes:
print(f"{code}: {description or 'Description unavailable'}")
def build_parser():
parser = argparse.ArgumentParser(description="Read simulated OBD-II data without changing vehicle state.")
subparsers = parser.add_subparsers(dest="mode", required=True)
subparsers.add_parser("dashboard", help="Show a refreshing terminal dashboard.")
log_parser = subparsers.add_parser("log", help="Write simulated data to CSV.")
log_parser.add_argument("--seconds", type=int, default=12)
log_parser.add_argument("--output", default="drive_log.csv")
subparsers.add_parser("dtc", help="Read stored diagnostic trouble codes.")
return parser
def main():
args = build_parser().parse_args()
if args.mode == "dashboard":
run_dashboard()
elif args.mode == "log":
run_log(args.seconds, args.output)
elif args.mode == "dtc":
run_dtc_check()
if __name__ == "__main__":
main()
Record a short simulated drive
A timestamp turns each sensor snapshot into evidence you can compare over time. The logger writes those snapshots to drive_log.csv once per second.
Before you run this, do you expect the terminal to show one final result or a stream of samples?
- Record a 12-second simulated drive by running this command:
python dashboard_logger.py log --seconds 12 --output drive_log.csv
What should I see?
This run takes about 12 seconds while the logger collects one snapshot per second. The terminal prints a numbered message for each sample.
The final message confirms that the samples were written to drive_log.csv. The file contains the header plus at least 12 timestamped telemetry rows.
The first few rows let you confirm that the timestamps and six sensor columns were saved correctly.
- Choose your platform to inspect the first five lines of drive_log.csv.
macOS
- Inspect the CSV header and first four samples by running this command:
head -n 5 drive_log.csv
What should I see?
The first line lists timestamp_utc and elapsed_seconds before the six sensor fields. The next four lines contain timestamps plus simulated numeric values.
Windows
- Inspect the CSV header and first four samples by running this command:
Get-Content drive_log.csv -TotalCount 5
What should I see?
The first line lists timestamp_utc and elapsed_seconds before the six sensor fields. The next four lines contain timestamps plus simulated numeric values.
Missing rows or sensor values?
- Confirm that the emulator process from earlier is still running.
- Check that your active terminal is still inside the project with .venv activated.
- Run the logging command again after restoring the emulator connection.
Help me troubleshoot an incomplete drive log.
Check stored codes safely
A stored-code check can return a list or an empty result. The app handles both outcomes without clearing codes or changing simulator state.
Before you run the check, do you expect the default car scenario to return a stored code?
- Query the simulator for stored diagnostic trouble codes by running this command:
python dashboard_logger.py dtc
What should I see?
You'll see No stored diagnostic trouble codes. because the default car scenario has an empty stored-code list. The explicit message proves that the empty response was handled successfully.
The app sends only the read-only GET_DTC query. It never calls CLEAR_DTC or sends a write command.
Did the code check fail?
- Confirm that the local emulator process from earlier is still running.
- Compare the read_stored_codes() function with the full-code reference.
- Check that main() routes the dtc mode to run_dtc_check().
Help me troubleshoot the read-only DTC check.
That is your evidence trail in place. Next, you'll turn the saved drive into a chart and a data-grounded explanation.
Chart and Explain the Drive
Your saved CSV file now preserves a simulated drive as timestamped rows. The next goal is to turn those rows into evidence you can inspect.
Rows of numbers make changes over time hard to see. A chart reveals the movement in each recorded value.
Matplotlib will create the visual evidence. Claude Code will use that evidence to write a cautious explanation.
In this step, get ready to:
- Generate a speed chart from your saved telemetry.
- Write reproducible facts about the recorded values.
- Create a cautious summary grounded in the project files.
Create deterministic analysis
Deterministic analysis uses fixed code to calculate facts from the same input. This gives Claude a factual base for its later explanation.
- Resume the Claude Code conversation for this project by running:
claude -c
What does this command do?
The claude -c command continues the most recent conversation in the current directory. Claude can build on the project context you already established.
- Paste this exact analysis request into Claude Code:
Create analyze_drive.py. It must read a CSV path from an optional positional argument that defaults to drive_log.csv. Use csv from the standard library and matplotlib.pyplot. Plot speed_kph over elapsed_seconds in the first of two vertically stacked subplots. Plot short_fuel_trim_pct and long_fuel_trim_pct in the second. Add titles, labels, legends, and save the figure as drive_plot.png at 150 dpi with a tight bounding box. Also write analysis_facts.txt containing the sample count, speed minimum and maximum, first and last coolant values, and minimum and maximum for both fuel trims. Reject a log with fewer than two rows. Do not invent diagnostic thresholds.
What will Claude build?
- The load_rows() function reads every row from drive_log.csv.
- The series() function converts recorded values into chart coordinates.
- The describe_range() function calculates reproducible minimums and maximums.
- The main() function creates the chart plus the facts file.
- Approve Claude's creation of analyze_drive.py.
- Return to the normal shell by typing /exit.
Before you run the analysis, which two files do you expect Python to create?
- Generate the chart and facts file by running:
python analyze_drive.py drive_log.csv
What should you see?
You should see Created drive_plot.png and analysis_facts.txt in the terminal. Good work. Your simulated telemetry now has a visual record plus a reproducible set of facts.
Analysis command not working?
- Confirm drive_log.csv still contains at least two data rows.
- Compare analyze_drive.py with the complete reference below.
Get targeted help with the analysis error.
✔️ Awesome, I've got everything!
Your analysis script is saved. Keep the generated chart and facts file for the next substep.
ⓧ I'd like to double check the full code
import argparse
import csv
from pathlib import Path
import matplotlib.pyplot as plt
def load_rows(csv_path):
with csv_path.open(newline="", encoding="utf-8") as csv_file:
return list(csv.DictReader(csv_file))
def series(rows, key):
points = []
for row in rows:
value = row.get(key, "")
if value not in ("", None):
points.append((float(row["elapsed_seconds"]), float(value)))
return [point[0] for point in points], [point[1] for point in points]
def describe_range(label, values, unit):
if not values:
return f"{label}: no values"
return f"{label}: min {min(values):.2f} {unit}, max {max(values):.2f} {unit}"
def main():
parser = argparse.ArgumentParser(description="Chart a simulated OBD-II drive log.")
parser.add_argument("csv_file", nargs="?", default="drive_log.csv")
args = parser.parse_args()
csv_path = Path(args.csv_file)
rows = load_rows(csv_path)
if len(rows) < 2:
raise SystemExit("The log needs at least two data rows.")
speed_x, speed = series(rows, "speed_kph")
short_x, short_trim = series(rows, "short_fuel_trim_pct")
long_x, long_trim = series(rows, "long_fuel_trim_pct")
_coolant_x, coolant = series(rows, "coolant_c")
figure, axes = plt.subplots(2, 1, figsize=(9, 6), sharex=True)
axes[0].plot(speed_x, speed, label="Speed")
axes[0].set(title="Simulated vehicle speed", ylabel="Speed (km/h)")
axes[0].legend()
axes[1].plot(short_x, short_trim, label="Short-term fuel trim")
axes[1].plot(long_x, long_trim, label="Long-term fuel trim")
axes[1].set(title="Simulated fuel trim", xlabel="Elapsed time (seconds)", ylabel="Fuel trim (%)")
axes[1].legend()
figure.savefig("drive_plot.png", dpi=150, bbox_inches="tight")
facts = [f"Samples: {len(rows)}", describe_range("Speed", speed, "km/h"), describe_range("Short-term fuel trim", short_trim, "%"), describe_range("Long-term fuel trim", long_trim, "%")]
if coolant:
facts.append(f"Coolant: first {coolant[0]:.2f} degC, last {coolant[-1]:.2f} degC")
else:
facts.append("Coolant: no values")
Path("analysis_facts.txt").write_text("\n".join(facts) + "\n", encoding="utf-8")
print("Created drive_plot.png and analysis_facts.txt")
if __name__ == "__main__":
main()
Write a data-grounded summary
A chart shows patterns without proving their cause. A responsible explanation separates visible observations from possible explanations.
- Resume the project conversation in Claude Code by running:
claude -c
Why resume the conversation?
The resumed conversation retains the project constraints from your earlier work. Claude can now examine the new evidence within that same context.
- Paste this exact summary request into Claude Code:
Read drive_log.csv and analysis_facts.txt, inspect drive_plot.png, and create drive_summary.md. Explain the simulated warm-up direction, when speed changed, and how short- and long-term fuel trim moved. Separate direct observations from possible explanations. State clearly that this is simulated data, not a vehicle diagnosis, and do not recommend replacing parts or clearing codes.
Why these boundaries matter
The prompt gives Claude three project artifacts to cross-check. It also prevents the summary from presenting simulated patterns as a real vehicle diagnosis.
The finished explanation can discuss possible causes. It cannot select a cause or recommend a repair from this simulation.
- Approve Claude's creation of drive_summary.md.
- Confirm Claude reports that drive_summary.md was created.
- Return to the normal shell by typing /exit.
Summary missing its safety boundary?
- Paste the exact summary request again if the file omits the simulated-data statement.
- Reject any suggestion to replace parts or clear diagnostic codes.
Get help reviewing the summary boundaries.
Inspect the finished evidence
The final check connects each generated artifact to a visible result. The folder confirms that the files exist.
Before you open the chart, what movement do you expect to see in speed and fuel trim?
- Press Cmd+Space on macOS or the Windows key on Windows to open system search.
- Type Finder on macOS or File Explorer on Windows.
- Press Enter to open the file browser.
- Navigate to the car-computer-reader folder inside your home folder.
You should see drive_plot.png, analysis_facts.txt, and drive_summary.md listed beside your existing project files.
- Open drive_plot.png from the car-computer-reader folder.
You should see vehicle speed in the top plot. You should see short-term plus long-term fuel trim in the bottom plot.
- Return to the car-computer-reader folder.
- Open drive_summary.md.
Your Markdown summary should cite patterns supported by the generated facts. It should state that the data is simulated plus that the result is not a vehicle diagnosis.
Strong finish. Your saved telemetry now supports a chart plus a bounded explanation.
Secret mission
Inject and Explain a Simulated Fault
Add a custom faulty_car scenario carrying P0420. Then prove your read-only code reader can retrieve the simulated fault and explain its limits without clearing anything.
Clean Up Your Resources
Clean Up Your Resources
Your local project has no ongoing cost. Choose a cleanup option below with the separate Claude Pro renewal in mind.
Cost warning
The local emulator stops when its terminal process ends. Claude Pro renews until canceled. Cancel at least 24 hours before renewal to avoid another billing period.
Resources you used:
- Local project folder containing the finished reader.
- Local ELM327-emulator process with faulty_car active.
- Claude Pro subscription with recurring billing.
Keep everything running
No action needed. Choose this if you want to continue testing the simulated car.
- Keep the project folder on your computer.
- Leave the local emulator terminal running while you test simulated responses.
- Keep Claude Pro active if you want continued access to Claude Code.
Pause - I'll come back to this later
Shut down the local process to free up your terminal. Your finished files stay available for another session.
- Stop the emulator by pressing Ctrl+C in its terminal.
- Run deactivate in every terminal where .venv remains active.
- Keep the project folder on your computer.
Your project is safely paused. The finished files remain ready for your next session.
Delete - I don't want to use this again
Remove the local project resources if you want to start fresh. This choice permanently removes your files.
- Stop the emulator by pressing Ctrl+C in its terminal.
- Run deactivate in every terminal where .venv remains active.
Deleting the folder is permanent. The platform instructions help you locate the correct folder through fault_scenario.py before removing it.
macOS
Finder can locate the project through a file you know is inside it.
- Press Cmd+Space to open Spotlight.
- Type Finder into Spotlight.
- Press Enter to open Finder.
- Search for fault_scenario.py in Finder.
- Select the folder that contains fault_scenario.py.
- Move the selected project folder to the Trash.
- Empty the Trash to remove the project files permanently.
A new search for fault_scenario.py should return no result.
Windows
File Explorer can locate the project through a file you know is inside it.
- Press the Windows key to open the search bar.
- Type File Explorer into the search bar.
- Press Enter to open File Explorer.
- Search for fault_scenario.py in File Explorer.
- Select the folder that contains fault_scenario.py.
- Move the selected project folder to the Recycle Bin.
- Empty the Recycle Bin to remove the project files permanently.
A new search for fault_scenario.py should return no result.
Claude Pro billing continues independently of your local files.
- Open Claude in your browser.
- Open Settings in Claude.
- Select Billing.
- Cancel Claude Pro at least 24 hours before renewal.
- Check the billing status to confirm the cancellation is recorded.
Cleanup complete. The emulator is stopped.
Nice Work!
Nice Work!
Excellent work! Your Claude Code project now turns simulated OBD-II data into a read-only evidence trail.
You've learned how to:
- Set up a cross-platform Python workspace through terminal prompts in Claude Code. Installed pinned dependencies inside an isolated virtual environment.
- Connected python-OBD to a local ELM327 emulator over a loopback TCP socket. Used that connection to display six read-only values in a refreshing terminal dashboard.
- Saved timestamped telemetry as CSV in drive_log.csv. Used Matplotlib to create drive_plot.png. Grounded drive_summary.md in generated facts.
- Added a custom simulated P0420 fault to faulty_car for the Secret Mission. Retrieved it through the read-only diagnostic trouble code path. Wrote fault_explanation.md without treating the code as a diagnosis.
Ready to quiz yourself?