can_interface.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include "can_interface.h"
  2. #include "can.h"
  3. #include <string.h>
  4. CAN_TxHeaderTypeDef tx_header;
  5. CAN_RxHeaderTypeDef rx_header;
  6. pcan_rx pcan_rx_back = NULL;
  7. pcan_tx pcan_tx_back = NULL;
  8. void can_rx_back_init(pcan_rx p_fun)
  9. {
  10. pcan_rx_back = p_fun;
  11. }
  12. void can_tx_back_init(pcan_tx p_fun)
  13. {
  14. pcan_tx_back = p_fun;
  15. }
  16. uint8_t can_write(uint32_t id, uint8_t id_type, uint8_t *p_data, uint8_t len)
  17. {
  18. uint32_t TxMailbox;
  19. if (id_type)
  20. {
  21. tx_header.ExtId = id; // 设置扩展标示符(29位)
  22. }
  23. else
  24. {
  25. tx_header.StdId = id_type; // 标准标识符为0
  26. }
  27. tx_header.IDE = id_type; // 使用扩展标识符
  28. tx_header.DLC = len; // 发送两帧信息
  29. if (len == 0)
  30. {
  31. tx_header.RTR = CAN_RTR_REMOTE; // 消息类型为远程帧
  32. }
  33. else
  34. {
  35. tx_header.RTR = CAN_RTR_DATA; // 消息类型为数据帧
  36. }
  37. if (HAL_CAN_AddTxMessage(&hcan, &tx_header, p_data, &TxMailbox) != HAL_OK) /* 发送消息 */
  38. {
  39. return 1;
  40. }
  41. return 0;
  42. }
  43. void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan_interface)
  44. {
  45. uint8_t rxbuf[8];
  46. if (hcan_interface->Instance == hcan.Instance)
  47. {
  48. HAL_CAN_GetRxMessage(hcan_interface, CAN_RX_FIFO0, &rx_header, rxbuf);
  49. if (pcan_rx_back != NULL)
  50. {
  51. pcan_rx_back(rx_header, rxbuf);
  52. }
  53. }
  54. }
  55. void HAL_CAN_TxMailbox0CompleteCallback(CAN_HandleTypeDef *hcan_interface)
  56. {
  57. if (hcan_interface->Instance == hcan.Instance)
  58. {
  59. if (pcan_tx_back != NULL)
  60. {
  61. pcan_tx_back();
  62. }
  63. }
  64. }
  65. void HAL_CAN_TxMailbox1CompleteCallback(CAN_HandleTypeDef *hcan_interface)
  66. {
  67. if (hcan_interface->Instance == hcan.Instance)
  68. {
  69. if (pcan_tx_back != NULL)
  70. {
  71. pcan_tx_back();
  72. }
  73. }
  74. }
  75. void HAL_CAN_TxMailbox2CompleteCallback(CAN_HandleTypeDef *hcan_interface)
  76. {
  77. if (hcan_interface->Instance == hcan.Instance)
  78. {
  79. if (pcan_tx_back != NULL)
  80. {
  81. pcan_tx_back();
  82. }
  83. }
  84. }