Machine Learning • Neural Networks • Automotive Engineering

Classic Engine Air Optimization

A theoretical approach to optimize classic engine performance by predicting air intake needs in real-time for TBI (Throttle Body Injection) equipped vehicles, ensuring peak efficiency and enhanced drivability. Powered by TensorFlow neural network running on Raspberry Pi 4. This concept brings modern intelligence to vintage automotive engineering.

TensorFlow Raspberry Pi 4 Classic Car TBI Vintage Performance

Project Overview

Developing an intelligent system to predict and optimize engine air intake for peak performance across varying environmental conditions.

The Challenge

Classic cars equipped with TBI (Throttle Body Injection) systems face unique challenges in maintaining optimal fuel-to-air ratios. Unlike modern EFI systems, TBI systems have limited adaptive capabilities, especially when environmental conditions change such as altitude or temperature variations.

Inspiration

Inspired by modern EFI technology, this project aims to retrofit classic TBI-equipped vehicles with intelligent air intake prediction, bringing 21st-century engine management to vintage automotive engineering.

The Solution

A TensorFlow neural network trained on TBI engine sensor inputs to predict optimal Mass Air Flow (MAF) values with high accuracy. The system integrates with existing TBI hardware through custom sensor interfaces, making it retrofittable to classic vehicles without major modifications.

Hardware

  • • Raspberry Pi 4 (8GB)
  • • TBI-compatible sensors
  • • Retrofittable interface

Software

  • • TensorFlow Neural Network
  • • Classic Car Optimization
  • • TBI-specific algorithms

Technical Architecture

Built with cutting-edge machine learning technologies for reliable, real-time engine optimization.

Neural Network

Multi-layer TensorFlow neural network trained on engine sensor data to predict MAF values with 95%+ accuracy.

Real-time Processing

Raspberry Pi 4 delivers real-time predictions with sub-millisecond latency for immediate engine adjustments.

Multi-sensor Input

Processes data from throttle position, temperature, pressure, and RPM sensors for comprehensive analysis.

Performance Results

Demonstrating exceptional accuracy and reliability across diverse testing conditions.

0.9836
R² Score
Model Accuracy
Explains 98.36% of variance in MAF predictions. Values closer to 1.0 indicate better model fit - this score demonstrates exceptional predictive accuracy.
2.96
RMSE
Root Mean Square Error
Average prediction error of 2.96 units. Lower values indicate better accuracy - this represents excellent precision for MAF sensor readings.
8.78
MSE
Mean Squared Error
Squared average of prediction errors. Lower values indicate better performance - this low MSE confirms consistent, reliable predictions.

Understanding the Metrics

R² Score (0.9836)

What it means: The model explains 98.36% of the variance in MAF values. This is exceptional - scores above 0.9 are considered excellent in machine learning.

Why it's good: Nearly perfect correlation between predictions and actual values, indicating the neural network has learned the underlying patterns effectively.

RMSE (2.9638)

What it means: On average, predictions are off by ±2.96 units from the true MAF value. This represents the typical prediction error.

Why it's excellent: For MAF sensors (typically measuring 0-500+ g/s), an error of ~3 units represents less than 1% deviation - highly precise for real-world applications.

MSE (8.7843)

What it means: The average of squared prediction errors. Penalizes larger errors more heavily than smaller ones.

Why it's good: Low MSE indicates consistent accuracy with few large prediction errors - critical for engine optimization where precision matters.

Visual Performance Analysis

MAF Prediction vs Actual Values

MAF Prediction vs True Value Chart

Neural network predictions (blue) vs actual MAF values with regression line and ideal prediction line for comparison

TensorFlow + TBI Sensor Integration

Real-time neural network inference with classic TBI engine data acquisition.

TensorFlow Neural Network

import tensorflow as tf
from tensorflow.lite import Interpreter
import numpy as np

# Load optimized TensorFlow Lite model
interpreter = Interpreter('maf_model.tflite')
interpreter.allocate_tensors()

def create_model():
    model = tf.keras.Sequential([
        tf.keras.layers.Dense(128, activation='relu',
                            input_shape=(8,)),
        tf.keras.layers.Dropout(0.2),
        tf.keras.layers.Dense(64, activation='relu'),
        tf.keras.layers.Dense(32, activation='relu'),
        tf.keras.layers.Dense(1, activation='linear')
    ])

    model.compile(
        optimizer='adam',
        loss='mse',
        metrics=['mae', 'accuracy']
    )
    return model

def predict_maf_realtime(sensor_data):
    # Preprocess inputs for neural network
    normalized_input = preprocess_sensors(sensor_data)

    # TensorFlow Lite inference
    input_details = interpreter.get_input_details()
    output_details = interpreter.get_output_details()

    interpreter.set_tensor(
        input_details[0]['index'],
        normalized_input
    )
    interpreter.invoke()

    prediction = interpreter.get_tensor(
        output_details[0]['index']
    )

    return denormalize_maf(prediction[0][0])

........

TBI Sensor Interface

import RPi.GPIO as GPIO
import spidev
import time
import threading
from collections import deque

# SPI interface for TBI sensor data
spi = spidev.SpiDev()
spi.open(0, 0)  # Bus 0, Device 0
spi.max_speed_hz = 1000000

# Real-time data buffer
live_data = deque(maxlen=100)

TBI_SENSORS = {
    'tps': {'channel': 0, 'scale': 5.0/1023},  # Throttle Position
    'rpm': {'channel': 1, 'scale': 8000/1023}, # RPM
    'map': {'channel': 2, 'scale': 100/1023},  # Manifold Pressure
    'iat': {'channel': 3, 'scale': 150/1023},  # Intake Air Temp
    'ect': {'channel': 4, 'scale': 200/1023},  # Engine Coolant Temp
    'o2': {'channel': 5, 'scale': 1.0/1023}    # O2 Sensor
}

def read_adc_channel(channel):
    """Read analog sensor data via SPI ADC"""
    adc = spi.xfer2([1, (8 + channel) << 4, 0])
    return ((adc[1] & 3) << 8) + adc[2]

def stream_tbi_data():
    """Continuous TBI sensor data acquisition"""
    while True:
        sensor_readings = {}

        for sensor, config in TBI_SENSORS.items():
            raw_value = read_adc_channel(config['channel'])
            sensor_readings[sensor] = raw_value * config['scale']

        # Add timestamp for real-time tracking
        sensor_readings['timestamp'] = time.time()
        live_data.append(sensor_readings)

        # Real-time TensorFlow prediction
        if len(live_data) >= 10:
            predicted_maf = predict_maf_realtime(
                sensor_readings
            )

            # TBI optimization feedback
            current_tps = sensor_readings.get('tps', 0)
            optimization_factor = calculate_tbi_optimization(
                predicted_maf, current_tps
            )

            print(f"TPS: {current_tps:.1f}%")
            print(f"Predicted MAF: {predicted_maf:.2f} g/s")
            print(f"TBI Optimization: {optimization_factor:.1f}%")

        time.sleep(0.05)  # 20Hz sampling rate

# Start real-time TBI monitoring
threading.Thread(
    target=stream_tbi_data,
    daemon=True
).start()

........

Key Features & Benefits

Revolutionary engine optimization technology with real-world applications.

Real-time Optimization

Continuously adjusts engine parameters based on live sensor data for optimal performance under changing conditions.

High Accuracy

98.36% R² score demonstrates exceptional prediction accuracy for reliable engine management.

Cost-Effective

Raspberry Pi 4 implementation makes advanced engine optimization accessible and affordable.

Environmental Adaptability

Automatically adjusts for altitude, temperature, and atmospheric pressure changes.

Fuel Efficiency

Optimizes air-fuel mixture for maximum efficiency and reduced emissions.

Retrofit Compatible

Modular design allows for easy integration with existing TBI systems through custom sensor interfaces, preserving classic car authenticity.

Technical Deep Dive

Understanding the engineering behind intelligent engine optimization.

Neural Network Architecture

Model Structure

  • Input Layer: 12 sensor inputs (throttle position, RPM, temperature, pressure, etc.)
  • Hidden Layers: Three dense layers (128, 64, 32 neurons) with ReLU activation
  • Dropout Layers: 20% dropout for regularization and overfitting prevention
  • Output Layer: Single neuron with linear activation for MAF prediction

Training Parameters

Optimizer: Adam
Loss Function: MSE
Batch Size: 32
Epochs: 25
Validation Split: 20%
Learning Rate: Adaptive

Hardware Implementation

Raspberry Pi 4

8GB RAM, ARM Cortex-A72 quad-core processor running TensorFlow Lite for optimized inference

Sensor Interface

GPIO and ADC interfaces for real-time sensor data acquisition from engine management system

Real-time Processing

Sub-millisecond inference times for immediate engine parameter adjustments