一、物理连接
二,流程分析
电脑连接CAN分析仪,电脑通过软件USB-CAN把can十六进制数据发到CAN分析仪。CAN分析仪连接CAN转以太网设备,数据通过CAN转以太网设备后,通过网线传送到单片机。这里面,CAN转以太网设置为TCP Client
模式,以CAN转以太网设备作为服务端,服务端IP地址为:192.168.0.7
,端口号为:20001
。单片机作为客户端,向服务端发起连接请求,接受来自服务端的数据。
三,客户端程序
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
#define SERV_IP "192.168.0.7"
#define SERV_PORT 20001
#define ITEMSIZE 3
#define WIDEIMAGE 500
int main()
{
int cfd,fd;
struct sockaddr_in serv_addr;
socklen_t serv_addr_len;
char readChar[ITEMSIZE],writeChar[1024];
int count,j=1;
cfd = socket(AF_INET,SOCK_STREAM,0);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERV_PORT);
inet_pton(AF_INET,SERV_IP,&serv_addr.sin_addr.s_addr);
connect(cfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
fd = open("can2.txt",O_RDONLY|O_WRONLY|O_CREAT);
while(1){
count = read(cfd,readChar,ITEMSIZE);
//write(fd,buf,sizeof(buf));
if(count==0){
break;
}
readChar[count]='\0';
count = sprintf(writeChar, "%02x%02x%02x ",
readChar[0]&0x00FF, readChar[1]&0x00FF, readChar[2]&0x00FF);
writeChar[count] = '\0';
write(fd, writeChar, count);
if(count < ITEMSIZE)
{
break;
}
if(j++%WIDEIMAGE == 0)
{
write(fd, "\n", 1);
}
}
close(fd);
close(cfd);
return 0;
}