ESP32c3 with RF24 and driver/twai

Dear Friends,

I'm trying to receive 5 bytes from a nrf24l01+ and re-transmit 2 bytes received trough canbus.

Using the attached code I'm able to receive every 100 ms all the bytes from the transmitter without lose any packets only if i disconnect the cables CanH and CanL.

The can bus works perfectly, I'm able to receive,filter and answer in all the conditions (max delay 0,2 ms measured).

Connecting CanH and CanL no problem with the CAN , but I start to lose a lot of packets from the nrf24l01.In this case the delay for a new data received can reach 1 second or more (the Transmitter send new data every 120 ms).

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include "driver/twai.h"

// Configurazione Pin nRF24L01
#define CE_PIN 7
#define CSN_PIN 8

// Configurazione Pin CAN 
#define CAN_TX_PIN GPIO_NUM_9
#define CAN_RX_PIN GPIO_NUM_10

#define DIP_1 0
#define DIP_2 1
#define DIP_3 2
#define DIP_4 3
#define RF_TIMEOUT_MS 400
unsigned long lastRfTime = 0;
bool rfTimedOut = true;

byte channel = 101;
byte DIP = 0;
byte indirizzo = 0;
byte thisSlaveAddress[5] = {0x00, 0x00, 0x00, 0x00, 0x00};
//RF24 radio(CE_PIN, CSN_PIN, 2000000);
RF24 radio(CE_PIN, CSN_PIN);
uint8_t rfData[5] = {0x00, 0x00, 0x00, 0x00, 0x00};

void setup() {
  pinMode(DIP_1, INPUT_PULLUP); // Consigliato INPUT_PULLUP se i DIP chiudono a GND
  pinMode(DIP_2, INPUT_PULLUP);
  pinMode(DIP_3, INPUT_PULLUP);
  pinMode(DIP_4, INPUT_PULLUP);
  
  Serial.begin(115200);
  delay(1000);

  
  // --- 2. Inizializzazione CAN Bus (TWAI) ---
  twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(CAN_TX_PIN, CAN_RX_PIN, TWAI_MODE_NORMAL);
  twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS();

  twai_filter_config_t f_config = {
    .acceptance_code = (0x589UL << 21),
    .acceptance_mask = ~(0x7FFUL << 21),
    .single_filter = true
  };

  if (twai_driver_install(&g_config, &t_config, &f_config) == ESP_OK) {
    Serial.println("Driver CAN installed filte ID 0x589.");
  } else {
    Serial.println("Error install driver CAN.");
    while (1);
  }

  if (twai_start() == ESP_OK) {
    Serial.println("Driver CAN start.");
  } else {
    Serial.println("Error start driver CAN.");
    while (1);
  }

  // --- 1. Inizializzazione RF24 ---
  DIP = digitalRead(DIP_1) | (digitalRead(DIP_2) << 1) | (digitalRead(DIP_3) << 2) | (digitalRead(DIP_4) << 3);
  indirizzo = channel + DIP;

  Serial.println("SimpleRx Starting");
  if (!radio.begin()) {
    Serial.println("nRF24L01 not responding!");
  }

  for (int i = 0; i < 5; i++) {
    thisSlaveAddress[i] = indirizzo;
  }

  radio.setDataRate(RF24_250KBPS);
  radio.setChannel(channel + DIP);
  radio.setPALevel(RF24_PA_LOW);
  radio.setAutoAck(false);
  radio.enableDynamicPayloads();
  
  radio.openReadingPipe(1, thisSlaveAddress);
  radio.printPrettyDetails();
  radio.startListening();
  Serial.println("nRF24L01 listening.");

}

void loop() {
  // --- FASE 1: Controllo ricezione dati da nRF24 ---
  if (radio.available()) {
    uint8_t len = radio.getDynamicPayloadSize();
    if (len == 5) {
      radio.read(&rfData, len);
      lastRfTime = millis();
      rfTimedOut = false;
      Serial.printf("RF (%d byte): 0x%02X 0x%02X\n", len, rfData[0], rfData[1]);
    } 
  }

  //**********************controllo timeout************
  if (!rfTimedOut && (millis() - lastRfTime > RF_TIMEOUT_MS)) {
    rfData[0] = 0x00;
    rfData[1] = 0x00;
    rfTimedOut = true;

  
   
    Serial.println("Timeout RF24 (>400ms)");
  }

  // --- FASE 2: Controllo ricezione messaggi CAN ---
  twai_message_t rx_msg;
// twai_receive(&rx_msg, 0);
  if (twai_receive(&rx_msg, 0) == ESP_OK) {
    
    //Serial.print("R ");
      inviaRispostaCAN();
    
 }
}

void inviaRispostaCAN() {
  
  twai_message_t tx_msg;
  tx_msg.identifier = 0x181;
  tx_msg.extd = 0;
  tx_msg.rtr = 0;
  tx_msg.data_length_code = 8;
  tx_msg.data[0] = 0xBA;
  tx_msg.data[1] = 0x02;
  if (rfTimedOut == false) tx_msg.data[2] = 0x01;
  if (rfTimedOut == true) tx_msg.data[2] = 0x00;
  tx_msg.data[3] = rfData[0]; // MSB pot
  tx_msg.data[4] = rfData[1]; // LSB pot
  tx_msg.data[5] = 0x02;      // version
  tx_msg.data[6] = 0x00;
  tx_msg.data[7] = 0x00;
 
  if (twai_transmit(&tx_msg, pdMS_TO_TICKS(1)) == ESP_OK) {
   //do nothing
 } else {
   Serial.println("Error send CAN.");
 }
}

Using decoupling capacitor or ferrite bead on supply or spi signal nothing change.

Does somebodys have an idea of what was wrong?

It is not obvious from your 'photo how the proct, and in particular the NF24 module is powered. Those modules are notorious for requiring a large current when transmitting

How are the elements of your project powered ?

The sn65hvd230 is supplyed by 5Vdc , the rest at 3.3V.There are an extra 220uF and 100nf capacitors welded directly on the nrf module. I used a mosfett level traslator between ESP32 and canbus transreceiver.

I tried even to separate the supply using an lm1117 only for the nrf module without result.

The first things I would try is changing the radio channel to see if any interference can be avoided: radio.setChannel(75);

Also I would definitely change the radio address from all 0s: byte thisSlaveAddress[5] = {0x00, 0x00, 0x00, 0x00, 0x00}; to byte thisSlaveAddress[5] = {0xCC, 0xCE, 0xEC, 0xEE, 0xC3};

Also set radio.setAutoAck = true so the radio engages in retries if a send fails.

I don't know if that will make a difference, but it is good practice.

Changing the dip-switch i set thr channel and the address too.....see the setup routine.

It works perfectly without the canbus wires,can h and canl disconnected an no problem on the nrf module.

The problem appears with the canbus connected.

To resume,same code......

Nrf module working without can bus wire connected and no packets loose.

With canbus wire connected, the canbus works perfectly,but I loose the 80% of the nrf packets.

Its got to be some sort of interference with the signals at the hardware level or a power issue.

I would next try to keep the bus connected and put the CAN controller in listen-only mode (on ESP32 TWAI that's TWAI_MODE_LISTEN_ONLY). The transceiver then never drives the bus.

  • Problem goes away: it's the transmit current, so it's power
  • Problem stays: it's interrupt load from received frames, or ground or common-mode
    noise.

Your system design means your Arduino must be able to do both jobs of receiving at the same time. It is acting as slave to both of the sending devices. That will cause the problem you are seeing. There is only one solution.

You need to redesign your system so your Arduino is able to control when the other devices send a message.You need to ASK each of the devices to send a message back to your Arduino and it needs to wait until it gets that message. Are you able to design such a system that will work with those devices?

Hi Paul,

it is working on this way.......when i receive the frame 0x589 i will answer with my packet derived from the data received by the nrf module.

HI TMRh20,

I tried to do something of different.....I removed from the code only the routine for the canbus sending........in normal mode.

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include "driver/twai.h"

// Configurazione Pin nRF24L01
#define CE_PIN 7
#define CSN_PIN 8

// Configurazione Pin CAN 
#define CAN_TX_PIN GPIO_NUM_9
#define CAN_RX_PIN GPIO_NUM_10

#define DIP_1 0
#define DIP_2 1
#define DIP_3 2
#define DIP_4 3
#define RF_TIMEOUT_MS 400
unsigned long lastRfTime = 0;
bool rfTimedOut = true;

byte channel = 101;
byte DIP = 0;
byte indirizzo = 0;
byte thisSlaveAddress[5] = {0x00, 0x00, 0x00, 0x00, 0x00};
//RF24 radio(CE_PIN, CSN_PIN, 2000000);
RF24 radio(CE_PIN, CSN_PIN);
uint8_t rfData[5] = {0x00, 0x00, 0x00, 0x00, 0x00};

void setup() {
  pinMode(DIP_1, INPUT_PULLUP); // Consigliato INPUT_PULLUP se i DIP chiudono a GND
  pinMode(DIP_2, INPUT_PULLUP);
  pinMode(DIP_3, INPUT_PULLUP);
  pinMode(DIP_4, INPUT_PULLUP);
  
  Serial.begin(115200);
  delay(1000);

  
  // --- 2. Inizializzazione CAN Bus (TWAI) ---
  twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(CAN_TX_PIN, CAN_RX_PIN, TWAI_MODE_NORMAL);
  twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS();

  twai_filter_config_t f_config = {
    .acceptance_code = (0x589UL << 21),
    .acceptance_mask = ~(0x7FFUL << 21),
    .single_filter = true
  };

  if (twai_driver_install(&g_config, &t_config, &f_config) == ESP_OK) {
    Serial.println("Driver CAN installed filte ID 0x589.");
  } else {
    Serial.println("Error install driver CAN.");
    while (1);
  }

  if (twai_start() == ESP_OK) {
    Serial.println("Driver CAN start.");
  } else {
    Serial.println("Error start driver CAN.");
    while (1);
  }

  // --- 1. Inizializzazione RF24 ---
  DIP = digitalRead(DIP_1) | (digitalRead(DIP_2) << 1) | (digitalRead(DIP_3) << 2) | (digitalRead(DIP_4) << 3);
  indirizzo = channel + DIP;

  Serial.println("SimpleRx Starting");
  if (!radio.begin()) {
    Serial.println("nRF24L01 not responding!");
  }

  for (int i = 0; i < 5; i++) {
    thisSlaveAddress[i] = indirizzo;
  }

  radio.setDataRate(RF24_250KBPS);
  radio.setChannel(channel + DIP);
  radio.setPALevel(RF24_PA_LOW);
  radio.setAutoAck(false);
  radio.enableDynamicPayloads();
  
  radio.openReadingPipe(1, thisSlaveAddress);
  radio.printPrettyDetails();
  radio.startListening();
  Serial.println("nRF24L01 listening.");

}

void loop() {
  // --- FASE 1: Controllo ricezione dati da nRF24 ---
  if (radio.available()) {
    uint8_t len = radio.getDynamicPayloadSize();
    if (len == 5) {
      radio.read(&rfData, len);
      lastRfTime = millis();
      rfTimedOut = false;
      Serial.printf("RF (%d byte): 0x%02X 0x%02X\n", len, rfData[0], rfData[1]);
    } 
  }

  //**********************controllo timeout************
  if (!rfTimedOut && (millis() - lastRfTime > RF_TIMEOUT_MS)) {
    rfData[0] = 0x00;
    rfData[1] = 0x00;
    rfTimedOut = true;

  
   
    Serial.println("Timeout RF24 (>400ms)");
  }

  // --- FASE 2: Controllo ricezione messaggi CAN ---
  twai_message_t rx_msg;
// twai_receive(&rx_msg, 0);
  if (twai_receive(&rx_msg, 0) == ESP_OK) {
    
    Serial.println("R ");
     // inviaRispostaCAN();
    
 }
}

void inviaRispostaCAN() {
  
  twai_message_t tx_msg;
  tx_msg.identifier = 0x181;
  tx_msg.extd = 0;
  tx_msg.rtr = 0;
  tx_msg.data_length_code = 8;
  tx_msg.data[0] = 0xBA;
  tx_msg.data[1] = 0x02;
  if (rfTimedOut == false) tx_msg.data[2] = 0x01;
  if (rfTimedOut == true) tx_msg.data[2] = 0x00;
  tx_msg.data[3] = rfData[0]; // MSB pot
  tx_msg.data[4] = rfData[1]; // LSB pot
  tx_msg.data[5] = 0x02;      // version
  tx_msg.data[6] = 0x00;
  tx_msg.data[7] = 0x00;
 
  if (twai_transmit(&tx_msg, pdMS_TO_TICKS(1)) == ESP_OK) {
   //do nothing
 } else {
   Serial.println("Error send CAN.");
 }
}

And this is the result......

09:23:08.713 -> R
09:23:08.713 -> RF (5 byte): 0x01 0xE0
09:23:08.854 -> RF (5 byte): 0x01 0xE0
09:23:08.962 -> RF (5 byte): 0x01 0xE1
09:23:09.033 -> RF (5 byte): 0x01 0xE1
09:23:09.145 -> RF (5 byte): 0x01 0xE1
09:23:09.257 -> RF (5 byte): 0x01 0xE1
09:23:09.368 -> RF (5 byte): 0x01 0xE1
09:23:09.472 -> RF (5 byte): 0x01 0xE1
09:23:09.537 -> R
09:23:09.612 -> RF (5 byte): 0x01 0xE1
09:23:09.689 -> RF (5 byte): 0x01 0xE1
09:23:09.804 -> RF (5 byte): 0x01 0xE1
09:23:09.912 -> RF (5 byte): 0x01 0xE1
09:23:10.029 -> RF (5 byte): 0x01 0xE1
09:23:10.105 -> RF (5 byte): 0x01 0xE1

So no packets lost from the nrf module.

I suppose there is a problem on the twai_transmit routine that is blocking the cycle.

Any advice?

I would then suspect power issues per my previous post.

Are you able to completely isolate the power to the RF24 module, like with a 3.3v battery? Remember to connect the negative/ground terminal to GND if you are.

You are sending packets pretty quickly, it may be worth also changing if (radio.available()) { to while (radio.available()) {

And when the two communications have collisions, how is that handled?

I tried with the while statement instead the if and nothing change.

Even using a big capacitor near the sn65hvd230 nothing change.

The negative is connect to gnd , like the rest of wirings in star configuration.

I know that i'm sending the packets quickly, but i need to use it like a real time remote control.

I will try with a battery , then I let you know.

Dear Paul,

Maybe i'm wrong , but how can i have collision if the sequence are made by the main loop and no interrupt are managed?

Do you mean that I have some command that block the main loop?

Do you suggest me to use a rtos to create a second task?

At the moment if I don't send any message ,RX only, on the can bus it works correctly.

Your code needs to ASK the nrf24 to send a message, then wait for the message and verify the message. Otherwise you are getting collisions causing you to miss messages. The use of timing messages will never be workable.

EUREKA!!!!!!!Some good news.......

Disconnected the +12Vdc that give me the supply, keeping connected gnd,canh and canl signals.

With a traditional transformer power bank work perfectly, as you said was a power failure.

I tested before the supply using an oscilloscope ,but no problem appeared.

I will try to filter it and i will see.

Thanks for the help.

Now I understand what you mean.

You are right, i will modify the code to do that.

Thanks Paul!