Teensy 4.1 CAN Bus Communication

abecede

New member
Hello everyone, I have a Teensy 4.1 board and I am having problems with communication using CAN bus.

To first test that the CAN bus on Teensy is working properly, I would like to send a message from CAN3 and receive it in CAN2. Is it possible to connect the pins directly (pin 0 to pin 31 and pin 1 to pin 30) or do I need to use transceivers?

I am using the following code but it seems that nothing is being sent. Does anyone have any idea on how can I do that?

Thanks in advance.

#include <FlexCAN_T4.h>
// Create instances for CAN1 and CAN2
FlexCAN_T4<CAN3, RX_SIZE_256, TX_SIZE_16> can3;
FlexCAN_T4<CAN2, RX_SIZE_256, TX_SIZE_16> can2;
void setup() {
Serial.begin(115200);
can3.begin();
can2.begin();
can3.setBaudRate(500000);
can2.setBaudRate(500000);
Serial.println("CAN3 and CAN2 initialized successfully.");
}
void loop() {
CAN_message_t msg;
msg.id = 0x123;
msg.len = 8;
msg.buf[0] = 1;
msg.buf[1] = 2;
msg.buf[2] = 3;
msg.buf[3] = 4;
msg.buf[4] = 5;
msg.buf[5] = 6;
msg.buf[6] = 7;
msg.buf[7] = 8;
can3.write(msg);
CAN_message_t receivedMsg;
if (can2.read(receivedMsg)) {
Serial.print("Received message on CAN2 - ID: 0x");
Serial.print(receivedMsg.id, HEX);
Serial.print(" Data: ");
for (int i = 0; i < receivedMsg.len; i++) {
Serial.print(receivedMsg.buf);
Serial.print(" ");
}
Serial.println();
}
delay(1000);
}
 
do I need to use transceivers?
Yes, you do.
I am using the following code but it seems that nothing is being sent. Does anyone have any idea on how can I do that?
Did your code compile without errors? I just tried it and ran into compile errors.
Reason is this line: serial.print(receivedMsg.buf);, that should be serial.print(receivedMsg.buf[i]);.

BTW: if you want to share code, you can use the </> button on the top-left. Then it looks like this:
C++:
#include <FlexCAN_T4.h>
// Create instances for CAN1 and CAN2
FlexCAN_T4<CAN3, RX_SIZE_256, TX_SIZE_16> can3;
FlexCAN_T4<CAN2, RX_SIZE_256, TX_SIZE_16> can2;

void setup() {
  Serial.begin(115200);
  can3.begin();
  can2.begin();
  can3.setBaudRate(500000);
  can2.setBaudRate(500000);
  Serial.println("CAN3 and CAN2 initialized successfully.");
}

void loop() {
  CAN_message_t msg;
  msg.id = 0x123;
  msg.len = 8;
  msg.buf[0] = 1;
  msg.buf[1] = 2;
  msg.buf[2] = 3;
  msg.buf[3] = 4;
  msg.buf[4] = 5;
  msg.buf[5] = 6;
  msg.buf[6] = 7;
  msg.buf[7] = 8;
  can3.write(msg);
  CAN_message_t receivedMsg;
  if (can2.read(receivedMsg)) {
    Serial.print("Received message on CAN2 - ID: 0x");
    Serial.print(receivedMsg.id, HEX);
    Serial.print(" Data: ");
    for (int i = 0; i < receivedMsg.len; i++) {
      Serial.print(receivedMsg.buf[i]);
      Serial.print(" ");
    }
    Serial.println();
  }
  delay(1000);
}

Paul
 
Back
Top