QT 環境下開發socketCan接口程序


使用頭文件

#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));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM