# Automotive Protocols

> Expert skill in BroadR-Reach automotive Ethernet physical layer (100BASE-T1) for cost-effective high-speed networking over single twisted pair. Covers 8 topics across automotive-protocols domain.

- Skill: `pangzhenying2025/automotive-protocols` (Agent Skill)
- Install (CLI): `npx skillmds@latest add pangzhenying2025/automotive-protocols`
- Raw SKILL.md: https://api.skillmd.com/api/skills/pangzhenying2025/automotive-protocols/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: pangzhenying2025 (https://skillmd.com/u/pangzhenying2025)
- Updated: 2026-09-22
- Page: https://skillmd.com/skills/pangzhenying2025/automotive-protocols

---


# Automotive Protocols

8 skill files covering automotive-protocols domain.

## Applicable Standards

- AEC-Q100 (Automotive component qualification)
- ANSI/TIA/EIA-644-A (LVDS Standard)
- ASPICE Level 3
- AUTOSAR 4.4
- AUTOSAR LIN Driver
- Automotive EMC compliance
- BroadR-Reach specification
- FPD-Link (Flat Panel Display Link)
- IEEE 1722 AVTP (Audio Video Transport Protocol)
- IEEE 802.1 AVB (Audio Video Bridging)
- IEEE 802.1 TSN (Time-Sensitive Networking)
- IEEE 802.3bw (100BASE-T1)
- ISO 14230 (KWP2000 over MOST)
- ISO 17458 (FlexRay Communications System)
- ISO 17987 (LIN Specification)
- ISO 26262 (Functional Safety)
- ISO 26262 ASIL-D (Functional Safety)
- LIN 2.2A specification
- MIPI CSI-2 (Camera Serial Interface)
- MOST Cooperation standard
- MOST Specification Rev. 3.0
- MOST150 (150 Mbps)
- OPEN Alliance TC1 specification
- OPEN Alliance TC8 specification
- OpenLDI (Open LVDS Display Interface)
- PSI5 Specification v2.3
- SAE J2602
- SAE J2716 (SENT Specification)
- SOME/IP (Scalable service-Oriented MiddlewarE)

## Instructions

## BroadR-Reach Protocol

## Core Competencies

Expert in BroadR-Reach physical layer for automotive Ethernet over single twisted pair.

### Physical Layer Characteristics
- Single unshielded twisted pair (UTP)
- 100 Mbps full-duplex bidirectional
- Cable length up to 15 meters (50 feet)
- Voltage range: -2V to +2V differential
- PAM3 (3-level Pulse Amplitude Modulation) encoding
- Frequency: 33.33 MHz fundamental

### Cable Requirements
- Unshielded twisted pair (UTP)
- AWG 24-26 gauge typical
- Impedance: 100 ohms ±15%
- Capacitance: <60 pF/m
- Low crosstalk for bundled cables
- Automotive temperature range (-40°C to +125°C)

### PHY Features
- Auto-negotiation (ANEG)
- Link partner detection
- Cable diagnostics (TDR - Time Domain Reflectometry)
- Sleep/wake functionality
- EMI/EMC compliance for automotive
- Power over Data Line (PoDL) support

### Connector Types
- FAKRA coaxial connector (legacy)
- USCAR connector
- Rosenberger HFM connector
- Amphenol Mini50 connector
- Automotive-grade shielding

## Design Approach

1. Physical Layer Design
   - Select appropriate cable type
   - Plan cable routing (avoid EMI sources)
   - Calculate maximum cable length
   - Choose connectors and terminations

2. PHY Configuration
   - Configure auto-negotiation
   - Set master/slave mode
   - Enable cable diagnostics
   - Configure sleep/wake behavior

3. EMC/EMI Mitigation
   - Proper grounding strategy
   - Common-mode choke selection
   - Cable shielding and routing
   - Ferrite bead placement

4. Validation and Testing
   - Eye diagram analysis
   - TDR cable verification
   - EMC compliance testing
   - Temperature stress testing

## Implementation Examples

### PHY Initialization
```c
// BroadR-Reach PHY configuration
typedef struct {
    uint8_t phyAddress;        // MDIO address (0-31)
    bool masterMode;           // Master/slave mode
    bool autoNegEnable;        // Auto-negotiation
    bool sleepEnable;          // Sleep mode support
    uint8_t ledMode;           // LED indicator config
} BRR_PhyConfig_t;

void BRR_InitPhy(const BRR_PhyConfig_t* config) {
    // Software reset
    BRR_MdioWrite(config->phyAddress, PHY_BASIC_CONTROL, PHY_RESET);

    // Wait for reset complete
    while (BRR_MdioRead(config->phyAddress, PHY_BASIC_CONTROL) & PHY_RESET);

    // Configure basic control register
    uint16_t bcr = 0;
    if (config->autoNegEnable) {
        bcr |= PHY_AUTONEG_ENABLE | PHY_RESTART_AUTONEG;
    }
    bcr |= PHY_FULL_DUPLEX | PHY_SPEED_100M;

    BRR_MdioWrite(config->phyAddress, PHY_BASIC_CONTROL, bcr);

    // Configure master/slave mode
    uint16_t msCfg = BRR_MdioRead(
        config->phyAddress,
        PHY_MASTER_SLAVE_CONTROL
    );

    if (config->masterMode) {
        msCfg |= PHY_MASTER_MODE;
    } else {
        msCfg &= ~PHY_MASTER_MODE;
    }

    BRR_MdioWrite(config->phyAddress, PHY_MASTER_SLAVE_CONTROL, msCfg);

    // Configure sleep mode
    if (config->sleepEnable) {
        uint16_t sleepReg = BRR_MdioRead(
            config->phyAddress,
            PHY_SLEEP_CONTROL
        );
        sleepReg |= PHY_SLEEP_ENABLE;
        BRR_MdioWrite(config->phyAddress, PHY_SLEEP_CONTROL, sleepReg);
    }

    // Configure LED indicators
    BRR_MdioWrite(config->phyAddress, PHY_LED_CONTROL, config->ledMode);
}
```

### Link Status Monitoring
```c
// Monitor link status and cable health
typedef struct {
    bool linkUp;
    bool masterMode;
    uint16_t linkSpeed;        // Mbps
    bool fullDuplex;
    uint16_t cableLength;      // Estimated meters
    bool cableFault;
} BRR_LinkStatus_t;

BRR_LinkStatus_t BRR_GetLinkStatus(uint8_t phyAddress) {
    BRR_LinkStatus_t status = {0};

    // Read basic status register
    uint16_t bsr = BRR_MdioRead(phyAddress, PHY_BASIC_STATUS);

    status.linkUp = (bsr & PHY_LINK_STATUS) != 0;

    if (status.linkUp) {
        // Read master/slave status
        uint16_t msStatus = BRR_MdioRead(
            phyAddress,
            PHY_MASTER_SLAVE_STATUS
        );
        status.masterMode = (msStatus & PHY_MASTER_STATUS) != 0;

        // Link speed is always 100 Mbps for BroadR-Reach
        status.linkSpeed = 100;
        status.fullDuplex = true;

        // Estimate cable length via TDR
        status.cableLength = BRR_EstimateCableLength(phyAddress);

        // Check for cable faults
        status.cableFault = BRR_CheckCableFault(phyAddress);
    }

    return status;
}
```

### Cable Diagnostics (TDR)
```c
// Time Domain Reflectometry for cable diagnostics
typedef enum {
    CABLE_OK,
    CABLE_OPEN,
    CABLE_SHORT,
    CABLE_CROSSTALK,
    CABLE_IMPEDANCE_MISMATCH
} BRR_CableFault_t;

BRR_CableFault_t BRR_RunCableDiagnostics(uint8_t phyAddress) {
    // Trigger TDR test
    uint16_t tdrCtrl = BRR_MdioRead(phyAddress, PHY_TDR_CONTROL);
    tdrCtrl |= PHY_TDR_START;
    BRR_MdioWrite(phyAddress, PHY_TDR_CONTROL, tdrCtrl);

    // Wait for completion (typically <1ms)
    uint32_t timeout = 1000;  // 1ms timeout
    while (timeout--) {
        tdrCtrl = BRR_MdioRead(phyAddress, PHY_TDR_CONTROL);
        if (!(tdrCtrl & PHY_TDR_START)) {
            break;
        }
        DelayUs(1);
    }

    // Read TDR result
    uint16_t tdrResult = BRR_MdioRead(phyAddress, PHY_TDR_RESULT);

    // Parse fault type
    uint8_t faultType = (tdrResult >> 12) & 0x0F;

    switch (faultType) {
        case 0x0: return CABLE_OK;
        case 0x1: return CABLE_OPEN;
        case 0x2: return CABLE_SHORT;
        case 0x3: return CABLE_CROSSTALK;
        case 0x4: return CABLE_IMPEDANCE_MISMATCH;
        default:  return CABLE_OK;
    }
}

uint16_t BRR_EstimateCableLength(uint8_t phyAddress) {
    // Read TDR distance measurement
    uint16_t tdrDistance = BRR_MdioRead(phyAddress, PHY_TDR_DISTANCE);

    // Convert to meters (formula vendor-specific)
    // Typical: distance_m = (tdr_value * 0.1)
    uint16_t lengthMeters = (tdrDistance * 10) / 100;

    return lengthMeters;
}
```

### Sleep/Wake Functionality
```c
// Enter sleep mode for power saving
void BRR_EnterSleepMode(uint8_t phyAddress) {
    // Send sleep request
    uint16_t sleepCtrl = BRR_MdioRead(phyAddress, PHY_SLEEP_CONTROL);
    sleepCtrl |= PHY_SLEEP_REQUEST;
    BRR_MdioWrite(phyAddress, PHY_SLEEP_CONTROL, sleepCtrl);

    // Wait for sleep acknowledge
    uint32_t timeout = 10000;  // 10ms
    while (timeout--) {
        sleepCtrl = BRR_MdioRead(phyAddress, PHY_SLEEP_CONTROL);
        if (sleepCtrl & PHY_SLEEP_ACK) {
            break;
        }
        DelayUs(1);
    }

    LogInfo("PHY entered sleep mode");
}

// Wake from sleep mode
void BRR_WakeFromSleep(uint8_t phyAddress) {
    // Method 1: Send wake pulse on MDC line
    BRR_SendWakePulse();

    // Method 2: Toggle PHY_WAKE pin (if available)
    // GPIO_SetPin(PHY_WAKE_PIN, HIGH);
    // DelayUs(100);
    // GPIO_SetPin(PHY_WAKE_PIN, LOW);

    // Wait for link to re-establish
    uint32_t timeout = 100000;  // 100ms
    while (timeout--) {
        uint16_t bsr = BRR_MdioRead(phyAddress, PHY_BASIC_STATUS);
        if (bsr & PHY_LINK_STATUS) {
            break;
        }
        DelayUs(1);
    }

    LogInfo("PHY woke from sleep mode");
}
```

### EMC/EMI Configuration
```c
// Configure EMI reduction features
void BRR_ConfigureEMI(uint8_t phyAddress) {
    // Enable spread spectrum clocking for EMI reduction
    uint16_t emiCtrl = BRR_MdioRead(phyAddress, PHY_EMI_CONTROL);

    emiCtrl |= PHY_SSC_ENABLE;           // Spread spectrum enable
    emiCtrl |= PHY_SLEW_RATE_LIMIT;      // Limit slew rate
    emiCtrl |= PHY_COMMON_MODE_FILTER;   // Enable CM filter

    BRR_MdioWrite(phyAddress, PHY_EMI_CONTROL, emiCtrl);

    // Configure output driver strength (reduce overshoot)
    uint16_t driverCfg = BRR_MdioRead(phyAddress, PHY_DRIVER_CONTROL);
    driverCfg &= ~PHY_DRIVER_STRENGTH_MASK;
    driverCfg |= PHY_DRIVER_STRENGTH_MEDIUM;  // Medium strength
    BRR_MdioWrite(phyAddress, PHY_DRIVER_CONTROL, driverCfg);
}
```

### Power over Data Line (PoDL) Configuration
```c
// Configure PoDL for powered devices (e.g., cameras)
typedef struct {
    bool enable;
    uint8_t powerClass;        // 0-8 (IEEE 802.3bu)
    uint16_t maxPowerMw;       // Maximum power in mW
} BRR_PoDL_Config_t;

void BRR_ConfigurePoDL(uint8_t phyAddress, const BRR_PoDL_Config_t* cfg) {
    if (!cfg->enable) {
        // Disable PoDL
        BRR_MdioWrite(phyAddress, PHY_PODL_CONTROL, 0);
        return;
    }

    // Configure PoDL PSE (Power Sourcing Equipment)
    uint16_t podlCtrl = 0;
    podlCtrl |= PHY_PODL_ENABLE;
    podlCtrl |= (cfg->powerClass << 8) & PHY_PODL_CLASS_MASK;

    BRR_MdioWrite(phyAddress, PHY_PODL_CONTROL, podlCtrl);

    // Set power limit
    BRR_MdioWrite(phyAddress, PHY_PODL_POWER_LIMIT, cfg->maxPowerMw);

    LogInfo("PoDL configured: Class %d, Max %d mW",
            cfg->powerClass, cfg->maxPowerMw);
}
```

## Use Case: Surround View Camera System

### Network Architecture
```
Central Camera ECU (Master)
  |
  +-- Front Camera (PD, Slave) - 5m cable
  +-- Rear Camera (PD, Slave) - 8m cable
  +-- Left Camera (PD, Slave) - 12m cable
  +-- Right Camera (PD, Slave) - 12m cable
```

### Cable Installation Guidelines
- Route away from high-power lines (>50cm separation)
- Avoid sharp bends (<50mm radius)
- Use cable ties every 15cm
- Ground shielding at one point only
- Install common-mode chokes near PHY

### PHY Configuration for Cameras
- Master mode at ECU
- Slave mode at cameras
- PoDL Class 3 (1-3.6W per camera)
- Auto-negotiation enabled
- Sleep mode for power saving when idle

## Deliverables

- PHY selection and configuration guide
- Cable routing diagram
- EMC test plan and results
- TDR cable verification reports
- Driver implementation (MDIO/PHY)
- Power budget analysis (PoDL)
- Integration test specifications

## Common Issues and Solutions

### Link Instability
- Check cable quality and length (<15m)
- Verify impedance matching (100 ohms)
- Test with TDR for cable faults
- Ensure proper master/slave configuration

### EMI Emissions Failures
- Enable spread spectrum clocking
- Add/relocate common-mode chokes
- Improve cable shielding and grounding
- Reduce driver output strength

### Auto-Negotiation Failures
- Verify both PHYs support ANEG
- Check for forced speed/duplex settings
- Monitor MDIO communication errors
- Validate PHY firmware version

### PoDL Power Issues
- Check cable resistance (<2 ohms for AWG24)
- Verify power class compatibility
- Monitor voltage drop along cable
- Ensure adequate PSE power budget

## Ethernet AVB/TSN Protocol

## Core Competencies

Expert in Automotive Ethernet with AVB/TSN for deterministic, low-latency networking.

### Physical Layer (100BASE-T1 / 1000BASE-T1)
- Single twisted pair (BroadR-Reach PHY)
- 100 Mbps or 1 Gbps data rate
- Cable length up to 15m (100BASE-T1) or 40m (1000BASE-T1)
- Point-to-point topology (switched network)
- PoE support for camera power

### TSN Technology Stack
- IEEE 802.1AS (Time Synchronization - gPTP)
- IEEE 802.1Qbv (Time-Aware Shaper - TAS)
- IEEE 802.1Qav (Credit-Based Shaper - CBS)
- IEEE 802.1Qcc (Stream Reservation Protocol - SRP)
- IEEE 802.1CB (Frame Replication and Elimination)

### Protocol Layers
```
Application (SOME/IP, DoIP, AVTP)
         |
Transport (UDP/TCP)
         |
Network (IPv4/IPv6)
         |
Data Link (AVB/TSN + VLAN)
         |
Physical (100BASE-T1 / 1000BASE-T1)
```

### Time-Sensitive Traffic Classes
- **Class A (CDT)**: Critical Data Traffic (e.g., ADAS sensor data)
  - Max latency: 2ms
  - Priority: Highest (PCP 6-7)
- **Class B**: Audio/Video streaming
  - Max latency: 50ms
  - Priority: High (PCP 4-5)
- **Best Effort**: Non-critical data
  - No latency guarantee
  - Priority: Normal (PCP 0-3)

## Design Approach

1. Network Architecture Design
   - Define topology (star, daisy-chain, hybrid)
   - Calculate bandwidth requirements
   - Plan VLAN and QoS strategy
   - Design fault tolerance (redundancy)

2. TSN Configuration
   - Configure gPTP domains
   - Design Time-Aware Shaper schedules
   - Allocate bandwidth per traffic class
   - Configure stream reservation

3. SOME/IP Service Design
   - Define service interfaces (FIDL)
   - Implement service discovery
   - Design event/method communication
   - Configure serialization

4. Validation and Testing
   - Timing verification (end-to-end latency)
   - Bandwidth utilization monitoring
   - Fault injection testing
   - TSN schedule validation

## Implementation Examples

### gPTP Time Synchronization (IEEE 802.1AS)
```c
// Initialize gPTP for time synchronization
typedef struct {
    uint8_t domainNumber;      // gPTP domain (0-127)
    uint8_t priority1;         // Grandmaster priority
    uint8_t priority2;
    uint8_t logSyncInterval;   // Sync message interval (log2)
    uint8_t logAnnounceInterval;
} gPTP_Config_t;

void gPTP_Init(const gPTP_Config_t* config) {
    // Configure as grandmaster or slave
    gPTP_SetDomain(config->domainNumber);
    gPTP_SetPriority(config->priority1, config->priority2);

    // Set sync interval (e.g., -3 = 125us, 0 = 1s)
    gPTP_SetSyncInterval(config->logSyncInterval);

    // Enable time synchronization
    gPTP_Enable();
}

// Get synchronized network time
uint64_t gPTP_GetNetworkTime(void) {
    uint64_t seconds;
    uint32_t nanoseconds;

    gPTP_GetTime(&seconds, &nanoseconds);

    return (seconds * 1000000000ULL) + nanoseconds;
}
```

### Time-Aware Shaper Configuration (IEEE 802.1Qbv)
```c
// TAS gate control list for deterministic scheduling
typedef struct {
    uint8_t gateStates;        // Bitmap of open gates (per TC)
    uint32_t timeIntervalNs;   // Interval duration
} TAS_GateEntry_t;

typedef struct {
    uint64_t basetime;         // Schedule start time (gPTP)
    uint32_t cycleTime;        // Total cycle duration
    TAS_GateEntry_t entries[8];
    uint8_t entryCount;
} TAS_Schedule_t;

// Example: 1ms cycle with dedicated slots for each traffic class
const TAS_Schedule_t adasSchedule = {
    .basetime = 0,             // Align to gPTP epoch
    .cycleTime = 1000000,      // 1ms cycle
    .entryCount = 4,
    .entries = {
        // Time slot 1: Critical ADAS data (300us)
        {.gateStates = 0b11000000, .timeIntervalNs = 300000},

        // Time slot 2: Audio/Video (400us)
        {.gateStates = 0b00110000, .timeIntervalNs = 400000},

        // Time slot 3: Best effort (200us)
        {.gateStates = 0b00001111, .timeIntervalNs = 200000},

        // Time slot 4: Guard band (100us)
        {.gateStates = 0b00000000, .timeIntervalNs = 100000}
    }
};

void TAS_ConfigureSchedule(uint8_t port, const TAS_Schedule_t* schedule) {
    // Program TAS registers on switch/endpoint
    TAS_SetBaseTime(port, schedule->basetime);
    TAS_SetCycleTime(port, schedule->cycleTime);

    for (uint8_t i = 0; i < schedule->entryCount; i++) {
        TAS_SetGateEntry(
            port,
            i,
            schedule->entries[i].gateStates,
            schedule->entries[i].timeIntervalNs
        );
    }

    // Enable TAS
    TAS_Enable(port);
}
```

### AVTP Camera Streaming (IEEE 1722)
```c
// AVTP stream for camera video
typedef struct {
    uint64_t streamId;         // Unique stream identifier
    uint8_t  destMac[6];       // Multicast MAC address
    uint16_t vlanId;
    uint8_t  priority;         // PCP value
    uint32_t maxFrameSize;     // Maximum video frame size
    uint16_t maxIntervalFrames;// Frames per interval
} AVTP_StreamConfig_t;

// Configure AVTP stream
void AVTP_ConfigureStream(const AVTP_StreamConfig_t* config) {
    // Register stream with SRP
    SRP_RegisterStream(
        config->streamId,
        config->destMac,
        config->vlanId,
        config->priority,
        config->maxFrameSize,
        config->maxIntervalFrames
    );

    // Configure talker
    AVTP_SetStreamId(config->streamId);
    AVTP_SetFormat(AVTP_FORMAT_H264);
}

// Send video frame via AVTP
void AVTP_SendVideoFrame(
    uint64_t streamId,
    uint8_t* frameData,
    uint32_t frameSize,
    uint64_t timestamp
) {
    // Build AVTP header
    AVTP_Header_t header;
    header.subtype = AVTP_SUBTYPE_CVF;  // Compressed Video Format
    header.streamId = streamId;
    header.timestamp = timestamp;       // gPTP timestamp
    header.streamDataLength = frameSize;
    header.sequenceNum = avtpSeqNum++;

    // Transmit with high priority
    ETH_SendPacket(
        &header,
        sizeof(header),
        frameData,
        frameSize,
        PRIORITY_HIGH
    );
}
```

### SOME/IP Service Implementation
```cpp
// SOME/IP service definition (Franca IDL)
/*
interface SensorFusion {
    version { major 1 minor 0 }

    method GetObjectList {
        out {
            ObjectList objects
        }
    }

    broadcast ObjectDetected {
        out {
            Object detectedObject
        }
    }
}
*/

// Service implementation
class SensorFusionService : public SomeIpService {
public:
    SensorFusionService() : SomeIpService(SERVICE_ID, INSTANCE_ID) {
        // Register methods
        RegisterMethod(METHOD_GET_OBJECT_LIST,
                      &SensorFusionService::HandleGetObjectList);

        // Offer service
        OfferService();
    }

    void HandleGetObjectList(const Message& request, Message& response) {
        // Gather object list from sensors
        ObjectList objects = GetTrackedObjects();

        // Serialize response
        Serializer serializer;
        serializer << objects;

        // Send response
        response.SetPayload(serializer.GetData());
        SendResponse(response);
    }

    void NotifyObjectDetected(const Object& obj) {
        // Broadcast event
        Message event(SERVICE_ID, INSTANCE_ID, EVENT_OBJECT_DETECTED);

        Serializer serializer;
        serializer << obj;

        event.SetPayload(serializer.GetData());
        BroadcastEvent(event);
    }

private:
    static const uint16_t SERVICE_ID = 0x1234;
    static const uint16_t INSTANCE_ID = 0x0001;
    static const uint16_t METHOD_GET_OBJECT_LIST = 0x0100;
    static const uint16_t EVENT_OBJECT_DETECTED = 0x8000;
};
```

### Stream Reservation Protocol (SRP)
```c
// Reserve bandwidth for AVB/TSN stream
typedef struct {
    uint64_t streamId;
    uint8_t  destMac[6];
    uint16_t vlanId;
    uint8_t  priority;
    uint32_t maxFrameSize;
    uint16_t maxIntervalFrames;
    uint32_t accumulatedLatency;  // Max end-to-end latency
} SRP_TalkerAdvertise_t;

SRP_Status_t SRP_AdvertiseStream(const SRP_TalkerAdvertise_t* talker) {
    // Calculate required bandwidth
    uint32_t bandwidth = (talker->maxFrameSize * 8 *
                         talker->maxIntervalFrames) / 125000;  // Mbps

    // Send MSRP Talker Advertise
    MSRP_SendTalkerAdvertise(
        talker->streamId,
        talker->destMac,
        talker->vlanId,
        talker->priority,
        talker->maxFrameSize,
        talker->maxIntervalFrames,
        talker->accumulatedLatency
    );

    // Wait for listener ready
    return SRP_WaitForListenerReady(talker->streamId, 1000);
}
```

## Use Case: ADAS Sensor Fusion System

### Network Architecture
```
Central ADAS ECU (Switch + Compute)
  |
  +-- Front Camera (1920x1080@30fps, H.264)
  +-- Rear Camera (1920x1080@30fps, H.264)
  +-- Left Camera (1280x720@30fps, H.264)
  +-- Right Camera (1280x720@30fps, H.264)
  +-- Front Radar (Object list @ 50Hz)
  +-- Lidar (Point cloud @ 10Hz)
  +-- Gateway ECU (CAN/FlexRay bridge)
```

### Bandwidth Requirements (1000BASE-T1)
- Front Camera: ~8 Mbps (H.264)
- Rear Camera: ~8 Mbps
- Left Camera: ~4 Mbps
- Right Camera: ~4 Mbps
- Radar: ~1 Mbps
- Lidar: ~20 Mbps
- Control/diagnostics: ~5 Mbps
- **Total**: ~50 Mbps (5% of 1 Gbps)

### TSN Configuration
- gPTP domain 0 for time sync (125us sync interval)
- TAS cycle: 1ms
- Critical traffic (radar, control): 300us window
- Video traffic: 600us window
- Best effort: 100us window

## Deliverables

- Network topology diagram
- TSN schedule configuration
- SOME/IP service definitions (FIDL)
- Bandwidth allocation spreadsheet
- gPTP configuration
- Driver/middleware implementation
- Integration test specifications
- Timing analysis report

## Common Issues and Solutions

### Time Sync Failures
- Verify gPTP domain configuration
- Check grandmaster selection algorithm
- Monitor path delay measurements
- Validate switch support for gPTP

### Packet Loss in Critical Traffic
- Check TAS gate schedule alignment
- Verify bandwidth reservation via SRP
- Monitor queue depths and drops
- Validate switch buffer configuration

### High Latency
- Optimize TAS schedule (reduce guard bands)
- Check for best-effort traffic starvation
- Verify priority tag configuration
- Analyze per-hop latency in switches

### SOME/IP Discovery Issues
- Check multicast routing configuration
- Verify service offer/find timing
- Monitor UDP port conflicts
- Validate firewall/VLAN settings

## FlexRay Protocol

## Core Competencies

Expert in FlexRay protocol for deterministic, fault-tolerant automotive communication.

### Physical Layer
- Dual-channel redundant communication (Channel A/B)
- Differential signaling at 10 Mbps
- Bus Guardian for fault isolation
- Star, bus, or hybrid topologies
- Cable length up to 24m per segment

### Data Link Layer
- Static and dynamic segments
- Time Division Multiple Access (TDMA)
- Cycle time: 1-16 ms (configurable)
- Frame size: 0-254 bytes payload
- CRC and frame checksums

### Communication Cycle Structure
```
|<------- Communication Cycle ------->|
| Static | Dynamic | Symbol | NIT     |
| Segment| Segment | Window | (Idle)  |
```

- Static Segment: Guaranteed deterministic slots
- Dynamic Segment: Flexible priority-based transmission
- Symbol Window: Network management
- Network Idle Time (NIT): Clock synchronization

### Timing and Synchronization
- Global time synchronization across all nodes
- Offset and rate correction
- Maximum drift tolerance: 1500 ppm
- Startup and wakeup procedures
- Coldstart vs. non-coldstart nodes

### Configuration Parameters
- Slot assignment (static/dynamic)
- Payload length per slot
- Base cycle multiplier
- Action point offsets
- Bus Guardian parameters

## Design Approach

1. Network Planning
   - Define communication matrix
   - Calculate bandwidth requirements
   - Assign static/dynamic slots
   - Configure redundancy strategy

2. Cluster Configuration
   - Set global cycle parameters
   - Configure clock synchronization
   - Define startup sequence
   - Set Bus Guardian parameters

3. Node Implementation
   - Configure Communication Controller (CC)
   - Implement AUTOSAR FlexRay Driver
   - Define frame triggering
   - Implement error handling

4. Validation and Testing
   - Timing verification (WCET analysis)
   - Fault injection testing
   - Startup sequence validation
   - Load and stress testing

## Implementation Examples

### Static Slot Configuration (AUTOSAR)
```c
// FlexRay static slot transmission
const Fr_LPduType staticPdu = {
    .FrameId = 10,              // Static slot ID
    .Channel = FR_CHANNEL_AB,   // Both channels
    .CycleRepetition = 1,       // Every cycle
    .CycleOffset = 0,
    .Payload = 16,              // 16 bytes (8 words)
    .HeaderCRC = 0x1A3          // Calculated CRC
};

// Transmit in static slot
Std_ReturnType result = Fr_TransmitTxLPdu(
    0,                          // Controller ID
    10,                         // Frame ID
    txData,                     // Payload pointer
    16                          // Length
);
```

### Dynamic Slot Usage
```c
// Dynamic segment configuration
const Fr_DynamicSlotConfig_t dynConfig = {
    .SlotId = 50,               // Dynamic slot start
    .PayloadLength = 32,
    .MinislotCount = 20,        // Number of minislots
    .Priority = 5               // Transmission priority
};

// Conditional transmission in dynamic segment
if (Fr_CheckTxLPduStatus(0, 50) == FR_TRANSMITTED) {
    Fr_TransmitTxLPdu(0, 50, dynamicData, 32);
}
```

### Startup Sequence
```c
// FlexRay startup procedure
void FlexRay_Startup(void) {
    // Initialize Communication Controller
    Fr_Init(&Fr_Config);

    // Configure cluster parameters
    Fr_ControllerInit(0);

    // Start communication (coldstart node)
    Fr_StartCommunication(0);

    // Wait for normal active state
    Fr_PocStateType pocState;
    do {
        Fr_GetPOCStatus(0, &pocState);
    } while (pocState != FR_POCSTATE_NORMAL_ACTIVE);
}
```

### Bus Guardian Configuration
```c
// Bus Guardian prevents babbling idiot
const Fr_BusGuardianConfig_t bgConfig = {
    .GuardianEnable = TRUE,
    .ActionPointOffset = 5,     // Macroticks before slot start
    .MaxTxDuration = 50,        // Maximum transmission time
    .MinislotDuration = 2       // Minislot size (macroticks)
};
```

## Use Case: Steer-by-Wire System

### Network Architecture
```
Steering ECU (Coldstart) <--Channel A/B--> Actuator ECU 1
                        <--Channel A/B--> Actuator ECU 2
                        <--Channel A/B--> Sensor ECU
```

### Communication Matrix
| Slot | Sender       | Data             | Cycle | Size |
|------|--------------|------------------|-------|------|
| 1    | Steering ECU | Steering Angle   | 5ms   | 16B  |
| 2    | Sensor ECU   | Torque Sensor    | 5ms   | 8B   |
| 3    | Actuator 1   | Position Status  | 5ms   | 12B  |
| 4    | Actuator 2   | Position Status  | 5ms   | 12B  |
| 50+  | All          | Diagnostics      | 20ms  | 32B  |

### Safety Considerations
- ASIL-D rated communication
- Dual-channel redundancy with voting
- Sequence counter for frame freshness
- CRC calculation for data integrity
- Timeout supervision on critical signals

## Deliverables

- FlexRay cluster specification (FIBEX XML)
- Node configuration files (AUTOSAR)
- Communication matrix documentation
- Driver implementation (C/C++)
- Timing analysis report (WCET)
- Integration test specifications
- Safety documentation (ISO 26262)

## Common Issues and Solutions

### Startup Failures
- Check coldstart node configuration
- Verify sync frame offsets
- Ensure clock tolerance within spec
- Validate Bus Guardian timing

### Communication Errors
- Monitor slot boundary violations
- Check CRC errors in frames
- Verify payload length configuration
- Analyze bus load in dynamic segment

### Timing Violations
- Reduce static segment load
- Optimize dynamic slot allocation
- Adjust action point offsets
- Verify interrupt latencies

## LIN Protocol

## Core Competencies

Expert in LIN protocol for cost-effective automotive sub-networks.

### Physical Layer
- Single-wire bidirectional bus
- Baud rates: 1 kbps to 20 kbps (typical: 9.6/19.2 kbps)
- Master-slave architecture (1 master, up to 16 slaves)
- Dominant (0V) and recessive (12V battery voltage)
- Bus length up to 40 meters
- No termination resistors required

### Protocol Architecture
- Master schedules all communication
- Slaves respond only when addressed
- Time-triggered schedule tables
- Event-triggered frames for efficiency
- Diagnostic services (ISO 14229 subset)

### Frame Structure
```
|<---------- LIN Frame ---------->|
| Header (Master)  | Response      |
| Break | Sync | ID| Data | CRC   |
```

- Break field: 13 dominant bits minimum
- Sync byte: 0x55 for baud rate sync
- Protected ID: 6-bit ID + 2 parity bits
- Data: 1-8 bytes
- Checksum: Classic or Enhanced

### LIN Frame Types
- Unconditional frames (standard data)
- Event-triggered frames (slave polling)
- Sporadic frames (conditional master transmission)
- Diagnostic frames (node configuration)

### Schedule Table Concept
```c
// Schedule table defines communication pattern
LIN_ScheduleTable_t SeatControlSchedule[] = {
    {FRAME_SeatPosition,    10},  // Every 10ms
    {FRAME_SeatMemory,      50},  // Every 50ms
    {FRAME_EventTrigger,   100},  // Slave event polling
    {FRAME_DiagRequest,    200},  // Diagnostic window
};
```

## Design Approach

1. Network Planning
   - Define master and slave nodes
   - Create signal database (LDF file)
   - Design schedule tables
   - Assign frame IDs (0x00-0x3F)

2. Master Node Implementation
   - Configure UART for LIN
   - Implement schedule table execution
   - Handle slave responses
   - Provide diagnostic services

3. Slave Node Implementation
   - Configure frame filters (ID match)
   - Implement response generation
   - Handle sleep/wakeup commands
   - Support node configuration

4. Validation and Testing
   - Bus timing verification
   - Frame error injection
   - Sleep/wakeup testing
   - EMC compliance testing

## Implementation Examples

### Master Frame Transmission (AUTOSAR)
```c
// LIN master sends unconditional frame
void Lin_MasterSendFrame(uint8 channel, Lin_PduType* pdu) {
    // Send break field (13-26 dominant bits)
    Lin_SendBreak(channel);

    // Send sync byte (0x55)
    Lin_SendByte(channel, LIN_SYNC_BYTE);

    // Calculate protected ID (ID + parity)
    uint8 protectedId = Lin_CalculateProtectedId(pdu->Id);
    Lin_SendByte(channel, protectedId);

    // Send data bytes
    for (uint8 i = 0; i < pdu->DataLength; i++) {
        Lin_SendByte(channel, pdu->Data[i]);
    }

    // Send checksum (enhanced)
    uint8 checksum = Lin_CalculateChecksum(
        protectedId,
        pdu->Data,
        pdu->DataLength,
        LIN_ENHANCED_CRC
    );
    Lin_SendByte(channel, checksum);
}
```

### Slave Response Handling
```c
// LIN slave responds to master request
void Lin_SlaveProcessFrame(uint8 id, uint8* data, uint8 len) {
    Lin_FrameResponseType response;

    // Check if this frame is for us
    if (Lin_GetFrameResponse(id, &response) == E_OK) {
        switch (response.Type) {
            case LIN_UNCONDITIONAL:
                // Provide response data
                Lin_PrepareResponse(
                    response.Data,
                    response.Length
                );
                break;

            case LIN_EVENT_TRIGGERED:
                // Check if we have data to send
                if (Lin_HasEventData()) {
                    Lin_PrepareResponse(
                        eventData,
                        eventLength
                    );
                }
                break;

            case LIN_DIAGNOSTIC:
                // Handle diagnostic request
                Lin_ProcessDiagnostic(data, len);
                break;
        }
    }
}
```

### Schedule Table Execution
```c
// Master executes schedule table
typedef struct {
    uint8 frameId;
    uint16 delayMs;
} Lin_ScheduleEntry_t;

const Lin_ScheduleEntry_t seatSchedule[] = {
    {0x10, 10},   // Seat position every 10ms
    {0x11, 20},   // Seat tilt every 20ms
    {0x12, 50},   // Memory recall every 50ms
    {0x3C, 100},  // Event-triggered every 100ms
    {0x3D, 200}   // Diagnostic every 200ms
};

void Lin_ExecuteSchedule(uint8 channel) {
    static uint8 scheduleIndex = 0;
    static uint32 lastTime = 0;

    uint32 currentTime = GetTickCount();
    const Lin_ScheduleEntry_t* entry = &seatSchedule[scheduleIndex];

    if (currentTime - lastTime >= entry->delayMs) {
        Lin_SendFrame(channel, entry->frameId);

        scheduleIndex = (scheduleIndex + 1) %
                        ARRAY_SIZE(seatSchedule);
        lastTime = currentTime;
    }
}
```

### Sleep/Wakeup Implementation
```c
// Sleep command (diagnostic frame 0x3C)
void Lin_GoToSleep(uint8 channel) {
    uint8 sleepCmd[] = {0x00, 0xFF, 0xFF, 0xFF,
                        0xFF, 0xFF, 0xFF, 0xFF};
    Lin_SendDiagnosticFrame(channel, 0x3C, sleepCmd, 8);

    // Enter sleep mode after frame transmission
    Lin_SetState(channel, LIN_STATE_SLEEP);
}

// Wakeup pulse (dominant signal 250-5000us)
void Lin_Wakeup(uint8 channel) {
    // Send dominant pulse (typically 500us)
    Lin_SendWakeupPulse(channel, 500);

    // Wait for bus recovery
    DelayUs(150);

    // Resume normal operation
    Lin_SetState(channel, LIN_STATE_OPERATIONAL);
}
```

### Node Configuration (LIN 2.x)
```c
// Assign NAD (Node Address for Diagnostics)
void Lin_AssignNAD(uint8 supplierId, uint16 functionId, uint8 newNAD) {
    uint8 configData[] = {
        0x06,                      // Service: Assign NAD
        (supplierId >> 8) & 0xFF,  // Supplier ID MSB
        supplierId & 0xFF,         // Supplier ID LSB
        (functionId >> 8) & 0xFF,  // Function ID MSB
        functionId & 0xFF,         // Function ID LSB
        newNAD,                    // New NAD
        0xFF, 0xFF
    };

    Lin_SendDiagnosticFrame(0, 0x3C, configData, 8);
}
```

## Use Case: Power Seat Control

### Network Architecture
```
Master (Body Control Module)
  |
  +-- Slave 1: Seat Position Sensor (NAD 0x01)
  +-- Slave 2: Lumbar Actuator (NAD 0x02)
  +-- Slave 3: Recline Motor (NAD 0x03)
  +-- Slave 4: Height Adjustment (NAD 0x04)
```

### Signal Database (LDF excerpt)
```ldf
Signals {
    SeatPositionFB: 8, 0, RightSeatSensor, AllNodes;
    LumbarPosition: 8, 0, LumbarActuator, AllNodes;
    ReclineAngle: 16, 0, ReclineMotor, AllNodes;
    SeatHeight: 8, 0, HeightActuator, AllNodes;
    MemoryRecall: 2, 0, BodyControlModule, AllNodes;
}

Frames {
    SeatStatus: 0x10, BodyControlModule, 4 {
        SeatPositionFB, 0;
        LumbarPosition, 8;
        ReclineAngle, 16;
    }

    SeatCommand: 0x11, BodyControlModule, 2 {
        MemoryRecall, 0;
        TargetPosition, 8;
    }
}

Schedule_tables {
    NormalOperation {
        SeatStatus delay 10 ms;
        SeatCommand delay 20 ms;
        EventTriggered delay 50 ms;
    }
}
```

### Timing Considerations
- Frame time: ~10ms at 9.6 kbps for 8-byte frame
- Schedule cycle: 100-200ms typical
- Response timeout: 14ms maximum (LIN spec)
- Sleep transition: within 4 seconds

## Deliverables

- LIN network description file (LDF)
- Node capability files (NCF)
- Master schedule tables
- Slave driver implementation
- Diagnostic database (ODX)
- Integration test specifications
- EMC test report

## Common Issues and Solutions

### Sync Byte Errors
- Check baud rate tolerance (<1.5%)
- Verify UART clock source stability
- Adjust slave sync detection

### Checksum Failures
- Verify classic vs. enhanced CRC mode
- Check endianness of multi-byte signals
- Validate checksum calculation algorithm

### Sleep/Wakeup Problems
- Check wakeup pulse duration (250-5000us)
- Verify bus pullup resistor (1k typical)
- Ensure all nodes support sleep mode

### Bus Contention
- Verify schedule table timing
- Check for rogue slave transmissions
- Monitor bus idle time between frames

## LVDS Protocol

## Core Competencies

Expert in LVDS for high-speed differential signaling in automotive applications.

### Physical Layer Characteristics
- Differential voltage: 247-454 mV (nominal 350 mV)
- Common-mode voltage: 1.2V typical
- Data rates: 155 Mbps to 1.2 Gbps per lane
- Low power consumption: ~3.5mW per driver
- Excellent EMI performance (differential cancellation)
- Point-to-point or multi-drop topologies

### Signal Characteristics
- Differential impedance: 100 ohms ±10%
- Rise/fall time: <500ps (typical 200ps)
- Propagation delay: ~50ps/inch on PCB
- Maximum cable length: 10m (shielded twisted pair)
- Skew tolerance: ±350ps between lanes

### LVDS Applications in Automotive
1. **Camera Interfaces**
   - Raw Bayer sensor data (MIPI CSI-2)
   - YUV422/RGB888 video formats
   - 1-4 data lanes + clock lane
   - Typical: 720p@30fps = 1 lane, 1080p@60fps = 4 lanes

2. **Display Interfaces**
   - FPD-Link (Texas Instruments)
   - OpenLDI for LCD panels
   - Instrument cluster displays
   - Head-up display (HUD) units

3. **Sensor Data**
   - Radar digital interface
   - Lidar point cloud transmission
   - High-speed ADC data

## Design Approach

1. Signal Integrity Design
   - Differential pair routing (100 ohm impedance)
   - Length matching between pairs (±5 mils)
   - Controlled impedance PCB stackup
   - Minimize vias and stubs

2. Serializer/Deserializer Selection
   - Choose appropriate SerDes chipset
   - Calculate required bandwidth
   - Plan for FEC (Forward Error Correction)
   - Consider diagnostic features

3. EMC/EMI Mitigation
   - Common-mode choke on cable
   - Proper grounding and shielding
   - Spread spectrum clocking
   - PCB layer stackup optimization

4. Validation and Testing
   - Eye diagram analysis
   - Jitter and skew measurement
   - BER (Bit Error Rate) testing
   - EMI radiated emissions testing

## Implementation Examples

### LVDS Driver Configuration
```c
// LVDS transmitter initialization
typedef struct {
    uint8_t laneCount;         // 1-4 lanes
    uint32_t bitRate;          // Mbps per lane
    bool spreadSpectrum;       // SSC for EMI reduction
    uint8_t outputSwing;       // 250mV, 300mV, 350mV, 400mV
    bool termination;          // 100 ohm termination
} LVDS_TxConfig_t;

void LVDS_InitTransmitter(const LVDS_TxConfig_t* config) {
    // Configure PLL for desired bit rate
    uint32_t pllFreq = config->bitRate * config->laneCount;
    LVDS_SetPLLFrequency(pllFreq);

    // Enable spread spectrum if requested
    if (config->spreadSpectrum) {
        LVDS_EnableSSC(SSC_CENTER_SPREAD, SSC_MODULATION_0_5_PERCENT);
    }

    // Configure output swing
    LVDS_SetOutputSwing(config->outputSwing);

    // Enable differential termination
    if (config->termination) {
        LVDS_EnableTermination(TERMINATION_100_OHM);
    }

    // Configure lane mapping
    for (uint8_t lane = 0; lane < config->laneCount; lane++) {
        LVDS_MapLane(lane, LANE_ENABLED);
    }

    // Enable transmitter
    LVDS_Enable(LVDS_TX);
}
```

### MIPI CSI-2 over LVDS (Camera Interface)
```c
// MIPI CSI-2 camera configuration
typedef struct {
    uint8_t dataLanes;         // 1-4 data lanes
    uint32_t pixelClock;       // MHz
    uint16_t width;            // Pixels
    uint16_t height;           // Lines
    uint8_t bitsPerPixel;      // 8, 10, 12, 16
    uint8_t virtualChannel;    // 0-3
} CSI2_CameraConfig_t;

void CSI2_ConfigureCamera(const CSI2_CameraConfig_t* config) {
    // Calculate required lane data rate
    // rate = (width * height * bpp * fps) / lanes
    uint32_t bytesPerFrame = config->width * config->height *
                             config->bitsPerPixel / 8;
    uint32_t laneDataRate = (bytesPerFrame * 30) / config->dataLanes;

    // Configure D-PHY (LVDS physical layer)
    CSI2_ConfigureDPhy(config->dataLanes, laneDataRate);

    // Configure CSI-2 receiver
    CSI2_SetVirtualChannel(config->virtualChannel);
    CSI2_SetDataType(CSI2_DT_RAW10);  // For 10-bit Bayer
    CSI2_SetImageSize(config->width, config->height);

    // Enable lanes
    for (uint8_t lane = 0; lane < config->dataLanes; lane++) {
        CSI2_EnableLane(lane);
    }

    // Start receiving
    CSI2_StartReceive();
}

// CSI-2 packet reception handler
void CSI2_ReceiveFrame(uint8_t* frameBuffer, uint32_t bufferSize) {
    // Wait for frame start (FS) packet
    CSI2_Packet_t packet;
    while (1) {
        if (CSI2_ReceivePacket(&packet) == CSI2_OK) {
            if (packet.dataType == CSI2_DT_FRAME_START) {
                break;
            }
        }

…(truncated)
