test-can.ino

Arduino Due · File : test-can.ino · Language : Arduino · Use case : Émettre et recevoir des trames CAN avec les contrôleurs de la Due

The SAM3X integrates two CAN controllers: with a plain SN65HVD230/TJA1050 transceiver the Due becomes a CAN bus node (automotive, industry). The due_can library hides the registers. Mind the 3.3 V pinout.

Hardware required

An Arduino Due (AT91SAM3X8E, ARM Cortex-M3 at 84 MHz) connected over USB to its « Programming » port. Caution: 3.3 V logic, never 5 V on the pins. 1 CAN transceiver (SN65HVD230 3.3 V recommended) + a 2nd node or a 120 Ω-terminated bus.

Wiring

Transceiver CANH/CANL to the bus (120 Ω at the ends), TXCAN/RXCAN to the Due CAN pins (GCC), VCC/GND.

How it works

CAN.init configures 500 kbit/s; writeTx queues a frame, readRx collects received frames (self loopback possible). In the Arduino IDE, select « Arduino Due (Programming Port) » then Upload; the serial monitor runs at the speed set in the code.

Going further

Filter IDs with CAN masks, or log an OBD-II bus through a 16-pin connector.

test-can.ino

// CAN0 de la Due (requiert un transceiver 5V/3.3V externe sur le bus).
#include <due_can.h>

void setup() {
  Serial.begin(115200);
  CAN.init(CAN_USE_GCC, 500000); // GCC = pinout standard, 500 kbit/s
  Serial.println(F("CAN0 emetteur/recepteur a 500 kbit/s"));
}

void loop() {
  static uint32_t compteur = 0;
  CAN_MESSAGE msg;
  msg.can_id = 0x123;
  msg.can_dlc = 4;
  msg.can_data_byte[0] = compteur & 0xFF;
  msg.can_data_byte[1] = (compteur >> 8) & 0xFF;
  msg.can_data_byte[2] = 0xAA;
  msg.can_data_byte[3] = 0x55;
  CAN.writeTx(msg);

  if (CAN.readRx(msg)) { // trame recue ?
    Serial.print(F("Rx id=0x")); Serial.println(msg.can_id, HEX);
  }
  compteur++;
  delay(200);
}

← Back to the board