diff --git a/src/CANController.cpp b/src/CANController.cpp index 0890eec..257fb5b 100644 --- a/src/CANController.cpp +++ b/src/CANController.cpp @@ -28,7 +28,7 @@ CANControllerClass::~CANControllerClass() { } -int CANControllerClass::begin(long /*baudRate*/) +int CANControllerClass::begin(long baudRate) { _packetBegun = false; _txId = -1; @@ -41,6 +41,7 @@ int CANControllerClass::begin(long /*baudRate*/) _rxDlc = 0; _rxLength = 0; _rxIndex = 0; + _baudrate = baudRate; return 1; } diff --git a/src/CANController.h b/src/CANController.h index cdaeb94..dc0455e 100644 --- a/src/CANController.h +++ b/src/CANController.h @@ -65,6 +65,7 @@ class CANControllerClass : public Stream { int _rxDlc; int _rxLength; int _rxIndex; + long _baudrate; uint8_t _rxData[8]; }; diff --git a/src/ESP32SJA1000.cpp b/src/ESP32SJA1000.cpp index 309e030..b855846 100644 --- a/src/ESP32SJA1000.cpp +++ b/src/ESP32SJA1000.cpp @@ -167,11 +167,21 @@ int ESP32SJA1000Class::endPacket() if (!CANControllerClass::endPacket()) { return 0; } + const uint16_t TIMEOUTVALUE = 2500; + uint16_t uiTimeOut = 0; // wait for TX buffer to free - while ((readRegister(REG_SR) & 0x04) != 0x04) { + while (((readRegister(REG_SR) & 0x04) != 0x04) && (uiTimeOut < TIMEOUTVALUE)) { yield(); + uiTimeOut++; } + if(uiTimeOut == TIMEOUTVALUE) { + // the lines below seem to do something in the CAN controller, allowing it to resume without reset + sleep(); + wakeup(); + return -1; /* get tx buff time out */ + } + uiTimeOut = 0; int dataReg; @@ -204,12 +214,19 @@ int ESP32SJA1000Class::endPacket() } // wait for TX complete - while ((readRegister(REG_SR) & 0x08) != 0x08) { + while (((readRegister(REG_SR) & 0x08) != 0x08) && (uiTimeOut < TIMEOUTVALUE)) { if (readRegister(REG_ECC) == 0xd9) { modifyRegister(REG_CMR, 0x1f, 0x02); // error, abort return 0; } yield(); + uiTimeOut++; + } + if(uiTimeOut == TIMEOUTVALUE) { + // the lines below seem to do something in the CAN controller, allowing it to resume without reset + sleep(); + wakeup(); + return -2; /* send msg time out */ } return 1;