CANDriver.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. struct CANFrame;
  2. class CANDriver {
  3. public:
  4. CANDriver();
  5. void init(uint32_t bitrate);
  6. bool send(const CANFrame &frame);
  7. bool receive(CANFrame &out_frame);
  8. private:
  9. struct Timings {
  10. uint16_t prescaler;
  11. uint8_t sjw;
  12. uint8_t bs1;
  13. uint8_t bs2;
  14. Timings()
  15. : prescaler(0)
  16. , sjw(0)
  17. , bs1(0)
  18. , bs2(0)
  19. { }
  20. };
  21. bool init_bus(const uint32_t bitrate);
  22. void init_once(bool enable_irq);
  23. bool computeTimings(uint32_t target_bitrate, Timings& out_timings);
  24. uint32_t bitrate;
  25. };
  26. /**
  27. * Raw CAN frame, as passed to/from the CAN driver.
  28. */
  29. struct CANFrame {
  30. static const uint32_t MaskStdID = 0x000007FFU;
  31. static const uint32_t MaskExtID = 0x1FFFFFFFU;
  32. static const uint32_t FlagEFF = 1U << 31; ///< Extended frame format
  33. static const uint32_t FlagRTR = 1U << 30; ///< Remote transmission request
  34. static const uint32_t FlagERR = 1U << 29; ///< Error frame
  35. static const uint8_t NonFDCANMaxDataLen = 8;
  36. static const uint8_t MaxDataLen = 8;
  37. uint32_t id; ///< CAN ID with flags (above)
  38. union {
  39. uint8_t data[MaxDataLen];
  40. uint32_t data_32[MaxDataLen/4];
  41. };
  42. uint8_t dlc; ///< Data Length Code
  43. CANFrame() :
  44. id(0),
  45. dlc(0)
  46. {
  47. memset(data,0, MaxDataLen);
  48. }
  49. CANFrame(uint32_t can_id, const uint8_t* can_data, uint8_t data_len, bool canfd_frame = false);
  50. bool operator!=(const CANFrame& rhs) const
  51. {
  52. return !operator==(rhs);
  53. }
  54. bool operator==(const CANFrame& rhs) const
  55. {
  56. return (id == rhs.id) && (dlc == rhs.dlc) && (memcmp(data, rhs.data, dlc) == 0);
  57. }
  58. bool isExtended() const
  59. {
  60. return id & FlagEFF;
  61. }
  62. bool isRemoteTransmissionRequest() const
  63. {
  64. return id & FlagRTR;
  65. }
  66. bool isErrorFrame() const
  67. {
  68. return id & FlagERR;
  69. }
  70. static uint8_t dlcToDataLength(uint8_t dlc);
  71. static uint8_t dataLengthToDlc(uint8_t data_length);
  72. /**
  73. * CAN frame arbitration rules, particularly STD vs EXT:
  74. * Marco Di Natale - "Understanding and using the Controller Area Network"
  75. * http://www6.in.tum.de/pub/Main/TeachingWs2013MSE/CANbus.pdf
  76. */
  77. bool priorityHigherThan(const CANFrame& rhs) const;
  78. bool priorityLowerThan(const CANFrame& rhs) const
  79. {
  80. return rhs.priorityHigherThan(*this);
  81. }
  82. };