WS_MCP2515.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include "WS_MCP2515.h"
  2. SPIClass spi;
  3. MCP_CAN CAN(&spi, MCP2515_CS_PIN);
  4. uint8_t buf[100] = {0};
  5. uint8_t Flag_Init = 1;
  6. long unsigned int canId = 0;
  7. uint32_t Count = 0;
  8. uint8_t receiveCANData(long unsigned int* canId, uint8_t* data) {
  9. if (CAN.checkReceive() == CAN_MSGAVAIL) { // Check whether CAN data is received
  10. uint8_t len = 0;
  11. if (CAN.readMsgBuf(canId, &len, data) == CAN_OK) {
  12. printf("CAN ID: 0x%x Data: ",*canId);
  13. for(int i = 0; i < len; i++) {
  14. printf("%x ", buf[i]);
  15. }
  16. printf(" \r\n");
  17. return len;
  18. }
  19. }
  20. return 0;
  21. }
  22. uint8_t sendCANData(long unsigned int canId, uint8_t len, uint8_t* data) {
  23. if(CAN.sendMsgBuf(canId, CAN_LEN, data) == CAN_OK) {
  24. printf("CAN message sent successfully!\r\n");
  25. return CAN_OK;
  26. } else {
  27. printf("Failed to send CAN message!\r\n");
  28. return 0;
  29. }
  30. }
  31. void MCP2515_Init() {
  32. spi.begin(SPI_CLK_PIN,SPI_MISO_PIN,SPI_MOSI_PIN);
  33. // Example Initialize the MCP2515 device
  34. if (CAN.begin(MCP_ANY, CAN_125KBPS, MCP_16MHZ) == CAN_OK){
  35. printf("MCP2515 Initialized Successfully!\r\n");
  36. CAN.setMode(MCP_NORMAL); // Set MCP2515 to normal mode
  37. printf("MCP2515 set to Normal Mode!\r\n");
  38. Flag_Init = 1;
  39. }
  40. else{
  41. Flag_Init = 0;
  42. printf("Error Initializing MCP2515...\r\n");
  43. }
  44. }
  45. void MCP2515_Loop() {
  46. if(Flag_Init){
  47. uint8_t len = receiveCANData(&canId, buf);
  48. if(len)
  49. printf("Received data: %d bytes of data were received\r\n\r\n",len);
  50. Count++;
  51. if(Count==70000)
  52. {
  53. Count = 0;
  54. unsigned char data[CAN_LEN] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77};
  55. sendCANData(CAN_ID,CAN_LEN,data); // Sending CAN messages
  56. }
  57. }
  58. else{
  59. Count++;
  60. if(Count==600000){
  61. Count = 0;
  62. printf("Error Initializing MCP2515...\r\n");
  63. MCP2515_Init();
  64. }
  65. }
  66. }