1、引入第三方库
链接:https://pan.baidu.com/s/1JC-Bi_Qgts5a-tGo28JcTQ?pwd=6533
提取码:6533
将第三方库 放在libs包里,并在pom文件中增加依赖
<dependency>
<groupId>libsocket-can-java</groupId>
<artifactId>libsocket-can-java</artifactId>
<version>0.1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/libsocket-can-java.jar</systemPath>
</dependency>
2、编写CAN口读写数据
@SpringBootApplication
public class LibsocketApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(LibsocketApplication.class, args);
System.out.println("Running tests!");
final CanSocket socket = new CanSocket(CanSocket.Mode.RAW);
final CanSocket.CanInterface canif = new CanSocket.CanInterface(socket, "can0");
socket.bind(canif);
System.out.println("bind success !");
//new CanSocket.CanId(0x5) 表示帧id,默认是标准帧,如果是扩展帧,使用这个 new CanSocket.CanId(0x5).setEFFSFF()
socket.send(new CanSocket.CanFrame(canif,
new CanSocket.CanId(0x5), new byte[] {
1,2,3,4,5,6,7,8}));
//循环不断接收新的消息
while (true) {
CanSocket.CanFrame canFrame = socket.recv(canif.getInterfaceIndex());
System.out.println("receive data length" + canFrame.getData().length);
System.out.println("canId:" + canFrame.getCanId());
System.out.println("data:" + bytesToHexString(canFrame.getData()));
}
public static String bytesToHexString(byte[] src){
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
}
3、在树莓派配置运行
3.1 配置 mcp2515模块的驱动
sudo nano /boot/config.txt
dtparam=i2c_arm=on
dtparam=i2c0,pins_44_45
dtoverlay=i2c-rtc,pcf8563,i2c_csi_dsi
dtparam=spi=on
dtoverlay=spi1-2cs
dtoverlay=mcp2515-can1,oscillator=12000000,interrupt=25
dtoverlay=mcp2515-can0,oscillator=12000000,interrupt=24
dtoverlay=mcp2515-can2,oscillator=12000000,interrupt=23
dtparam=audio=on
验证安装
dmesg | grep -i can
3.2 安装CAN口工具
sudo apt install can-utils
3.3 启动CAN口
sudo ip link set can0 up type can bitrate 500000
或者
##回环发送 可用于测试当前程序消息的收发
sudo ip link set can0 up type can bitrate 500000 loopback on
3.4 查看CAN口网络
ifconfig -a
3.5 模拟发送CAN消息
发送CAN消息
cansend can0 300#1880E0A80100
监听CAN口
candump can0 -L
文章评论