Try Embedded

ISO-TP: send 50 bytes over 8-byte CAN frames

Two Nucleo-F446RE boards on one CAN bus: a tester splits a 50-byte message into ISO-TP frames, and the ECU paces it with flow control.

Communication · Advanced

In a real product: Engine control unit calibration download (Automotive): A workshop tester writes calibration data into an ECU over CAN with ISO-TP.

A classic CAN frame carries at most 8 bytes, but a diagnostic message can be thousands of bytes long. ISO 15765-2, called ISO-TP, is the transport layer that cuts a long message into frames and joins them again. Every car's diagnostics run on it.

Here the board on the left is the tester and the one on the right is an ECU. The tester sends a 50-byte calibration block on id 0x7E0. The ECU answers on 0x7E8: first with flow control, then with a short reply saying how many bytes it got and their checksum. Both programs are bare-metal C on bxCAN CAN1 (PA11, PA12) at 500 kbit/s.

What you'll learn

  • The four ISO-TP frame types: single frame (0x), first frame (1x), consecutive frame (2x) and flow control (3x)
  • How the receiver paces the sender with flow control: BS (block size) and STmin (the gap between frames)
  • The 4-bit sequence number that wraps from F to 0, and the timeouts (N_Bs, N_Cr) that end a broken transfer
  • Using a bxCAN filter bank in list mode, so a node only receives the one id it listens to

How it works

A message of 7 bytes or less fits in one single frame: byte 0 is 0 plus the length. A longer one starts with a first frame: 1 and a 12-bit length in bytes 0 and 1, then the first 6 data bytes.

The sender then stops and waits for flow control. The ECU here answers 30 02 05: 0 = clear to send, block size 2, STmin 5 ms. The tester sends two consecutive frames (21, 22), each holding 7 more bytes and at least 5 ms apart. Then it waits for the next flow control. A block size of 0 would mean "send everything, no more flow control".

Each consecutive frame's low nibble counts 1, 2, …, F, 0, 1. The receiver checks it, so a lost or repeated frame is noticed instead of silently corrupting the data.

If no flow control comes within 1000 ms (N_Bs), the tester gives up. If the ECU waits more than 1000 ms for the next consecutive frame (N_Cr), it drops what it has.

Every frame is sent with all 8 bytes and the unused ones padded with AA, as most vehicle networks require.

The filter bank is in list mode: instead of an id and a mask, it holds the exact ids that may pass. The ECU lists only 0x7E0 and the tester only 0x7E8, so neither sees its own traffic or anything else on the bus.

Try this

  • Change the ECU's BLOCK_SIZE to 0 and watch the tester send all seven consecutive frames after one flow control.
  • Set STMIN_MS to 20 and compare the transfer time the tester prints.
  • Make the tester skip sequence number 3 (sn++ twice once) and see the ECU report a wrong sequence number.
  • Change the ECU's BUFFER_SIZE to 32: it answers the first frame with an overflow (32) and the tester stops.

main.c

// Bare-metal C on the Nucleo-F446RE: no Arduino core and no HAL. CMSIS names every register.
// The TESTER: sends a 50-byte calibration block to the ECU with ISO-TP (ISO 15765-2) on CAN id 0x7E0, and reads
// the ECU's flow control and reply on 0x7E8. bxCAN CAN1 on PA11 (RX) and PA12 (TX) at 500 kbit/s.
#include <stdio.h>
#include <string.h>
#include "stm32f4xx.h"

#define TX_ID 0x7E0   // tester -> ECU
#define RX_ID 0x7E8   // ECU -> tester

static volatile uint32_t ms;
void SysTick_Handler(void) { ms++; }
static void delay_ms(uint32_t t) { uint32_t s = ms; while (ms - s < t) {} }

int __io_putchar(int ch) {
  while (!(USART2->SR & USART_SR_TXE)) {}
  USART2->DR = ch;
  return ch;
}

static void print_frame(const char *what, const uint8_t *f) {
  printf("%-3s", what);
  for (int i = 0; i < 8; i++) printf(" %02X", f[i]);
  printf("\r\n");
}

// ---- CAN: bxCAN CAN1, polled ----------------------------------------------------------------------------------
static int can_init(void) {
  CAN1->MCR = CAN_MCR_INRQ;                                  // out of Sleep, into Initialization mode
  while (!(CAN1->MSR & CAN_MSR_INAK)) {}
  // 16 MHz / (BRP 2 x 16 quanta) = 500 kbit/s, sampled at 87.5 %.
  CAN1->BTR = (1u << CAN_BTR_TS2_Pos) | (12u << CAN_BTR_TS1_Pos) | (1u << CAN_BTR_BRP_Pos);
  // Filter bank 0, 32-bit list mode: only RX_ID passes, into FIFO 0.
  CAN1->FMR = (14u << CAN_FMR_CAN2SB_Pos) | CAN_FMR_FINIT;
  CAN1->FA1R &= ~1u;
  CAN1->FS1R |= 1u;
  CAN1->FM1R |= 1u;
  CAN1->FFA1R &= ~1u;
  CAN1->sFilterRegister[0].FR1 = RX_ID << 21;
  CAN1->sFilterRegister[0].FR2 = RX_ID << 21;
  CAN1->FA1R |= 1u;
  CAN1->FMR &= ~CAN_FMR_FINIT;
  CAN1->MCR &= ~CAN_MCR_INRQ;                                // Normal mode once the bus is idle
  uint32_t start = ms;
  while (CAN1->MSR & CAN_MSR_INAK) if (ms - start > 50) return 0;
  return 1;
}

// Sends 8 bytes: len of data, the rest padded with AA. Returns 0 if the last frame is still not acknowledged.
static int can_send(const uint8_t *data, int len) {
  uint8_t f[8];
  memset(f, 0xAA, 8);
  memcpy(f, data, len);
  uint32_t start = ms;
  while (!(CAN1->TSR & CAN_TSR_TME0)) {
    if (ms - start > 10) { CAN1->TSR = CAN_TSR_ABRQ0; return 0; }
  }
  CAN_TxMailBox_TypeDef *box = &CAN1->sTxMailBox[0];
  box->TIR = TX_ID << CAN_TI0R_STID_Pos;
  box->TDTR = 8;
  box->TDLR = f[0] | f[1] << 8 | f[2] << 16 | (uint32_t)f[3] << 24;
  box->TDHR = f[4] | f[5] << 8 | f[6] << 16 | (uint32_t)f[7] << 24;
  box->TIR |= CAN_TI0R_TXRQ;
  return 1;
}

// Waits up to timeout ms for a frame; returns 1 with its 8 bytes in f, or 0.
static int can_receive(uint8_t *f, uint32_t timeout) {
  uint32_t start = ms;
  while (!(CAN1->RF0R & CAN_RF0R_FMP0)) if (ms - start >= timeout) return 0;
  uint32_t lo = CAN1->sFIFOMailBox[0].RDLR, hi = CAN1->sFIFOMailBox[0].RDHR;
  for (int i = 0; i < 4; i++) { f[i] = lo >> (8 * i); f[4 + i] = hi >> (8 * i); }
  CAN1->RF0R = CAN_RF0R_RFOM0;                               // release it: the next one comes up
  return 1;
}

// ---- ISO-TP sender --------------------------------------------------------------------------------------------
// Sends one message; returns NULL when done, or why it stopped.
static const char *isotp_send(const uint8_t *msg, uint16_t len) {
  uint8_t f[8];
  if (len <= 7) {                                            // single frame
    f[0] = len;
    memcpy(f + 1, msg, len);
    print_frame("SF", f);
    return can_send(f, len + 1) ? NULL : "no acknowledge";
  }
  f[0] = 0x10 | (len >> 8);                                  // first frame: 12-bit length, 6 data bytes
  f[1] = len & 0xFF;
  memcpy(f + 2, msg, 6);
  if (!can_send(f, 8)) return "no acknowledge";
  print_frame("FF", f);
  uint16_t sent = 6;
  uint8_t sn = 1;
  while (sent < len) {
    uint8_t fc[8];
    for (;;) {                                               // wait for clear to send
      if (!can_receive(fc, 1000)) return "N_Bs timeout: no flow control";
      if ((fc[0] & 0xF0) != 0x30) continue;                  // not flow control
      print_frame("FC", fc);
      if ((fc[0] & 0x0F) == 1) continue;                     // wait: another flow control follows
      if ((fc[0] & 0x0F) == 2) return "the ECU's buffer is too small (overflow)";
      break;
    }
    uint8_t bs = fc[1];
    uint32_t stmin = fc[2] <= 0x7F ? fc[2] : 1;              // F1-F9 are 100-900 us: 1 ms is enough
    for (uint8_t n = 0; sent < len && (bs == 0 || n < bs); n++) {
      if (n) delay_ms(stmin);
      uint16_t chunk = len - sent > 7 ? 7 : len - sent;
      memset(f, 0xAA, 8);
      f[0] = 0x20 | (sn++ & 0x0F);                           // consecutive frame and its sequence number
      memcpy(f + 1, msg + sent, chunk);
      if (!can_send(f, chunk + 1)) return "no acknowledge";
      print_frame("CF", f);
      sent += chunk;
    }
  }
  return NULL;
}

static const char CALIBRATION[] = "CAL v1.2;idle=850rpm;fan=92C;limit=6500rpm;crc=ok.";

int main(void) {
  SysTick_Config(SystemCoreClock / 1000);
  RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
  RCC->APB1ENR |= RCC_APB1ENR_USART2EN | RCC_APB1ENR_CAN1EN;
  // PA2, PA3: AF7 (USART2); PA11, PA12: AF9 (CAN1).
  GPIOA->MODER = (GPIOA->MODER & ~(0xFu << 4 | 0xFu << 22)) | (0xAu << 4) | (0xAu << 22);
  GPIOA->AFR[0] = (GPIOA->AFR[0] & ~(0xFFu << 8)) | (0x77u << 8);
  GPIOA->AFR[1] = (GPIOA->AFR[1] & ~(0xFFu << 12)) | (0x99u << 12);
  USART2->BRR = SystemCoreClock / 115200;
  USART2->CR1 = USART_CR1_TE | USART_CR1_UE;

  printf("Tester: %s\r\n", can_init() ? "on the bus" : "no CAN bus");
  delay_ms(20);                                              // let the ECU start

  for (uint32_t round = 1;; round++) {
    uint16_t len = sizeof CALIBRATION - 1;
    printf("\r\nSending %u bytes to the ECU\r\n", len);
    uint32_t start = ms;
    const char *error = isotp_send((const uint8_t *)CALIBRATION, len);
    if (error) printf("Stopped: %s\r\n", error);
    uint8_t reply[8];
    if (!error && can_receive(reply, 1000) && reply[0] == 4 && reply[1] == 0x01) {
      printf("ECU got %u bytes, checksum %02X, in %lu ms\r\n", reply[2] << 8 | reply[3], reply[4],
             (unsigned long)(ms - start));
    } else if (!error) {
      printf("No reply from the ECU\r\n");
    }
    delay_ms(1000);
  }
}

ecu.c

// Bare-metal C on the Nucleo-F446RE: no Arduino core and no HAL. CMSIS names every register.
// The ECU: receives ISO-TP messages on CAN id 0x7E0, pacing the sender with flow control (block size, STmin), and
// answers on 0x7E8 with a single frame: 01, the length it got and an 8-bit checksum. LD2 (PA5) flashes per message.
#include <stdio.h>
#include <string.h>
#include "stm32f4xx.h"

#define TX_ID 0x7E8   // ECU -> tester
#define RX_ID 0x7E0   // tester -> ECU
#define BLOCK_SIZE 2  // consecutive frames between flow controls (0: no more flow control)
#define STMIN_MS 5    // the sender waits at least this long between consecutive frames
#define BUFFER_SIZE 128

static volatile uint32_t ms;
void SysTick_Handler(void) { ms++; }

int __io_putchar(int ch) {
  while (!(USART2->SR & USART_SR_TXE)) {}
  USART2->DR = ch;
  return ch;
}

// ---- CAN: bxCAN CAN1, polled ----------------------------------------------------------------------------------
static int can_init(void) {
  CAN1->MCR = CAN_MCR_INRQ;
  while (!(CAN1->MSR & CAN_MSR_INAK)) {}
  CAN1->BTR = (1u << CAN_BTR_TS2_Pos) | (12u << CAN_BTR_TS1_Pos) | (1u << CAN_BTR_BRP_Pos);   // 500 kbit/s
  CAN1->FMR = (14u << CAN_FMR_CAN2SB_Pos) | CAN_FMR_FINIT;
  CAN1->FA1R &= ~1u;
  CAN1->FS1R |= 1u;
  CAN1->FM1R |= 1u;                                          // list mode: only RX_ID
  CAN1->FFA1R &= ~1u;
  CAN1->sFilterRegister[0].FR1 = RX_ID << 21;
  CAN1->sFilterRegister[0].FR2 = RX_ID << 21;
  CAN1->FA1R |= 1u;
  CAN1->FMR &= ~CAN_FMR_FINIT;
  CAN1->MCR &= ~CAN_MCR_INRQ;
  uint32_t start = ms;
  while (CAN1->MSR & CAN_MSR_INAK) if (ms - start > 50) return 0;
  return 1;
}

static int can_send(const uint8_t *data, int len) {
  uint8_t f[8];
  memset(f, 0xAA, 8);
  memcpy(f, data, len);
  uint32_t start = ms;
  while (!(CAN1->TSR & CAN_TSR_TME0)) {
    if (ms - start > 10) { CAN1->TSR = CAN_TSR_ABRQ0; return 0; }
  }
  CAN_TxMailBox_TypeDef *box = &CAN1->sTxMailBox[0];
  box->TIR = TX_ID << CAN_TI0R_STID_Pos;
  box->TDTR = 8;
  box->TDLR = f[0] | f[1] << 8 | f[2] << 16 | (uint32_t)f[3] << 24;
  box->TDHR = f[4] | f[5] << 8 | f[6] << 16 | (uint32_t)f[7] << 24;
  box->TIR |= CAN_TI0R_TXRQ;
  return 1;
}

static int can_receive(uint8_t *f, uint32_t timeout) {
  uint32_t start = ms;
  while (!(CAN1->RF0R & CAN_RF0R_FMP0)) if (ms - start >= timeout) return 0;
  uint32_t lo = CAN1->sFIFOMailBox[0].RDLR, hi = CAN1->sFIFOMailBox[0].RDHR;
  for (int i = 0; i < 4; i++) { f[i] = lo >> (8 * i); f[4 + i] = hi >> (8 * i); }
  CAN1->RF0R = CAN_RF0R_RFOM0;
  return 1;
}

// ---- ISO-TP receiver ------------------------------------------------------------------------------------------
static void flow_control(uint8_t status) {
  uint8_t fc[3] = { 0x30 | status, BLOCK_SIZE, STMIN_MS };
  can_send(fc, 3);
}

// Waits for one message; returns its length, or a negative number saying what went wrong.
static int isotp_receive(uint8_t *buf, uint16_t cap) {
  uint8_t f[8];
  for (;;) {
    if (!can_receive(f, 0xFFFFFFFF)) return -1;
    uint8_t type = f[0] >> 4;
    if (type == 0) {                                         // single frame
      uint8_t len = f[0] & 0x0F;
      if (len == 0 || len > 7) continue;
      memcpy(buf, f + 1, len);
      return len;
    }
    if (type != 1) continue;                                 // a stray frame: ignore it
    uint16_t len = (f[0] & 0x0F) << 8 | f[1];
    if (len > cap) { flow_control(2); return -2; }           // overflow
    memcpy(buf, f + 2, 6);
    uint16_t got = 6;
    uint8_t sn = 1, block = 0;
    flow_control(0);                                         // clear to send
    while (got < len) {
      if (!can_receive(f, 1000)) return -3;                  // N_Cr timeout
      if ((f[0] >> 4) != 2) continue;
      if ((f[0] & 0x0F) != (sn & 0x0F)) return -4;           // wrong sequence number
      sn++;
      uint16_t chunk = len - got > 7 ? 7 : len - got;
      memcpy(buf + got, f + 1, chunk);
      got += chunk;
      if (BLOCK_SIZE && ++block == BLOCK_SIZE && got < len) { block = 0; flow_control(0); }
    }
    return len;
  }
}

int main(void) {
  SysTick_Config(SystemCoreClock / 1000);
  RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
  RCC->APB1ENR |= RCC_APB1ENR_USART2EN | RCC_APB1ENR_CAN1EN;
  GPIOA->MODER = (GPIOA->MODER & ~(0xFu << 4 | 0xFu << 22 | 3u << 10)) | (0xAu << 4) | (0xAu << 22) | (1u << 10);
  GPIOA->AFR[0] = (GPIOA->AFR[0] & ~(0xFFu << 8)) | (0x77u << 8);
  GPIOA->AFR[1] = (GPIOA->AFR[1] & ~(0xFFu << 12)) | (0x99u << 12);
  USART2->BRR = SystemCoreClock / 115200;
  USART2->CR1 = USART_CR1_TE | USART_CR1_UE;

  printf("ECU: %s, block size %d, STmin %d ms\r\n", can_init() ? "on the bus" : "no CAN bus", BLOCK_SIZE, STMIN_MS);
  static uint8_t buffer[BUFFER_SIZE + 1];
  for (;;) {
    int len = isotp_receive(buffer, BUFFER_SIZE);
    if (len == -2) { printf("Refused a message longer than %d bytes\r\n", BUFFER_SIZE); continue; }
    if (len == -3) { printf("N_Cr timeout: the rest of the message never came\r\n"); continue; }
    if (len == -4) { printf("Wrong sequence number: message dropped\r\n"); continue; }
    if (len < 0) continue;
    uint8_t sum = 0;
    for (int i = 0; i < len; i++) sum += buffer[i];
    buffer[len] = 0;
    GPIOA->ODR ^= 1u << 5;
    printf("Got %d bytes: %s\r\n", len, (char *)buffer);
    uint8_t reply[5] = { 4, 0x01, len >> 8, len & 0xFF, sum };   // single frame: 4 bytes
    can_send(reply, 5);
  }
}

Lessons behind it