QT 环境下开发socketCan接口程序

来源:互联网 发布:php打印数组到文件 编辑:程序博客网 时间:2024/05/17 03:14

使用头文件

#include <QMainWindow>
#include "QTimer"
#include "QTime"
#include "QMessageBox"
#include <QSocketNotifier>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "fcntl.h"
#include "sys/ioctl.h"
#include "sys/stat.h"
#include <net/if.h>

#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <linux/can.h>
#include <linux/can/raw.h>
#define PF_CAN 29

定义相关变量

struct sockaddr_can addr;
struct ifreq ifr;
struct can_frame frame;
int canfd;

接口初始化

canfd=socket(PF_CAN, SOCK_RAW, CAN_RAW);
if(canfd==-1)
{
perror("socket");
exit(1);
}
strcpy(ifr.ifr_name, "can0" );
if(ioctl(canfd, SIOCGIFINDEX, &ifr))
{
qDebug("ioctl");

}
addr.can_family = PF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
if(bind(canfd, (struct sockaddr *)&addr, sizeof(addr))<0)
{
qDebug("bind");

}

发送数据

memcpy(frame.data,buf,8);
frame.can_dlc=8;
frame.can_id=0x32;
write(canfd, &frame, sizeof(struct can_frame));

接收数据

read(canfd, &frame, sizeof(struct can_frame));

1 0
原创粉丝点击