Linux Qt Can.zip

所需积分/C币:42 2020-07-23 17:12:11 273KB ZIP
8
收藏 收藏
举报

Linux下面QT写Can通信程序,网络上有很多例子都是互相抄的;本人因为项目原因,通过源代码Socket函数,写了完整的程序,含有2个案例;分享给大家; 这里主要是包含几个步骤,1:绑定Socket;2:cna/can1的设置,3:波特率的设置(如果发送和接收波特率不一致肯定不行的);4:发送;5:接收处理; 下面就贴出部分代码: void MyWindow::startcan(int number) { int ret = 0; //can先关闭 设置好波特率后 再开启can if(number == 0) //can0 { system("ifconfig can0 down");//先关闭 system("ip link set can0 up type can bitrate 50000 triple-sampling on");//设置波特率 system("ifconfig can0 up");//再开启 } else //can1 { system("ifconfig can1 down");//先关闭 system("ip link set can1 up type can bitrate 50000 triple-sampling on");//设置波特率 system("ifconfig can1 up");//再开启 } socket = ::socket(PF_CAN,SOCK_RAW,CAN_RAW); struct ifreq ifr; strcpy((char *)(ifr.ifr_name),number == 0 ? "can0" : "can1"); ioctl(socket,SIOCGIFINDEX,&ifr); addr.can_family = AF_CAN; addr.can_ifindex = ifr.ifr_ifindex; ret = bind(socket,(struct sockaddr*)&addr,sizeof(addr)); if (ret < 0) { QMessageBox::about(this,"error","in bind error"); exit(1); } zyhapi->OpenCan(50000); ArmCan = new Thread(zyhapi,socket,port); ArmCan->start(); } void MyWindow::stopcan(int number) { if(ArmCan) { ArmCan->stop(); ArmCan->terminate(); ArmCan->wait(); } zyhapi->CloseCan(number); } //发送 void MyWindow::on_sendbtn_clicked() { /* struct can_frame frame; memset(&frame,0,sizeof(struct can_frame)); std::string str=ui->edit->text().toStdString(); if(str.length() > 8) { QMessageBox::about(this,"error","length of send string must less than 8 bytes"); return; } */ struct can_frame frame; memset(&frame,0,sizeof(struct can_frame)); char buf[8]={0X20,0XFF,0X01,0X02,0X03,0X04,0XFF,0XFF}; frame.can_id = 0x00000020;//发出去的帧ID即:0X00000020 frame.can_dlc = 8;//帧数据长度 for(int i=0;i<frame.can_dlc;i++) { frame.data[i]=buf

...展开详情
立即下载 低至0.43元/次 身份认证VIP会员低至7折
一个资源只可评论一次,评论内容不能少于5个字
  • 分享王者

    成功上传51个资源即可获取
关注 私信 TA的资源
上传资源赚积分or赚钱
    最新推荐