< * 아두이노 간 CAN 통신 : MCP2515 사용 *>
◈ 아두이노는 캔 통신을 지원하지 않는다.
◈ 통신 모듈이 필요하며, 주로 MCP2515 모듈을 사용한다.
◈ MCP2515 모듈
▷ MCU와 SPI 프로토콜을 이용하여 통신합다.
▷ 모듈에는 2핀 헤더가 2개 있다.
- 출력 터미널 단자(청색) 근처의 핀헤더는 터미널 단자와 연결되어 있고,
- 하단의 나머지 하나는 종단 저항 설정용 이다.
- 종단 저항은 통신 실패를 방지하기 위해 사용되며, 통신의 끝부분 장비에만 설정하면 된다.
- MCP2515 모듈은 16MHz와 8MHz 모델로 나누어져 있다.
* 모델별로 사용하는 라이브러리가 다르기 때문에 주의하여야 한다.
----- < MCP2515 모듈 CAN 통신 : SEND 소스 코드 > -------------------------------------------
송신 측 MCP2515 모듈 연결하기
CS --> D10, SO --> D12 , SI --> D11 , SCK --> D13 , 버튼 --> GND, D3 , LED --> GND, D2, 저항 연결
#include <mcp_can.h>
#include <SPI.h>
MCP_CAN CAN0(10);
struct CAN_Data_Frame {
long unsigned int can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
unsigned char can_dlc; /* data length code: 0 .. 8 */
byte data[8];
};
struct CAN_Data_Frame Charging_Status;
byte data[8] = {0x00, 0x01, 0x02, 0x03, 0xBB, 0xAA, 0x06, 0x07};
int Charger_Charging_Status(){
Charging_Status.can_id = 0x40001;
Charging_Status.can_dlc = 8;
Charging_Status.data[0] = 0xFF;
Charging_Status.data[1] = 0x03;
Charging_Status.data[2] = 0x00;
Charging_Status.data[3] = 0x00;
Charging_Status.data[4] = 0x00;
Charging_Status.data[5] = 0x01;
Charging_Status.data[6] = 0x01;
Charging_Status.data[7] = 0x00;
return 0;
}
void setup() {
Serial.begin(9600);
if(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK)
Serial.println("MCP2515 Initialized Successfully!");
else
Serial.println("Error Initializing MCP2515...");
CAN0.setMode(MCP_NORMAL);
}
void loop() {
Charger_Charging_Status();
if (Serial.available()){
CAN0.sendMsgBuf(Charging_Status.can_id , 1, Charging_Status.can_dlc,Charging_Status.data);
Serial.println(" data Sending...");
}
delay(1000);
}
----- < MCP2515 모듈 CAN 통신 : Receive 소스 코드 > -------------------------------------------
수신 측 MCP2515 모듈 연결
CS --> D10 , SO --> D12 , SI --> D11 , SCK --> D13 , INT(수신 측만 연결) --> D2 , LED --> GND, D3, 저항 연결
#include <mcp_can.h>
#include <SPI.h>
#define CAN0_INT 2
MCP_CAN CAN0(10);
byte data[8] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
long unsigned int rxId=0;
unsigned char len = 0;
unsigned char rxBuf[8];
void setup() {
Serial.begin(9600);
if(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK) Serial.println("MCP2515 Initialized Successfully!");
else Serial.println("Error Initializing MCP2515...");
CAN0.setMode(MCP_NORMAL);
}
void loop() {
if(!digitalRead(CAN0_INT)){
CAN0.readMsgBuf(&rxId, &len, rxBuf);
Serial.println("Receive Data");
Serial.print("canID : 0x");
Serial.println(rxId, HEX);
for(int i=0;i<8;i++){
Serial.print(rxBuf[i], HEX);
Serial.print("\t");
}
Serial.print("\n");
}
}