/* 字符串转换成10进制
*处理帧id 和 数据字符串*/
int chartoHex(char c)
{
int temp =0;
if(c>='0' && c<='9')
{
temp = c - 48;
}
if(c>='a' && c<='f')
{
temp = c - 87;
}
if(c>='A' && c<='F')
{
temp = c - 55;
}
return temp;
}
/* 发送can消息
*1.从界面获取id和数据字符串
*2.转换成16进制发送*/
void MainWindow::on_canmsgsend_pushButton_clicked()
{
if(ui->canmsgID_linedit->text().isEmpty() || ui->canmsg_lenedit->text().isEmpty())
{
ui->cansendNotice_lable->setStyleSheet("QLabel{color:rgb(255, 0, 0)}");
ui->cansendNotice_lable->setText("ID或数据为空");
return;
}
ui->cansendNotice_lable->setText("");
int temp = 0;
uint32_t sfid=0;
QString idstr = ui->canmsgID_linedit->text(); //获取id字符串
for (int i=0; i<idstr.size(); i++) //转成16进制
{
temp = chartoHex(idstr[i].toLatin1()); //转成16进制
sfid += temp*pow(16,idstr.size()-(i+1)); //转成10进制
}
//1122334455667788
uint8_t canData[8] = {0};
uint8_t msgSize = 0, oddflag=0;
QString msgStr = ui->canmsg_lenedit->text(); //获取消息字符串
if(msgStr.size()%2 == 0)
{
msgSize = msgStr.size(); // 如果是偶数
}
else
{
msgSize = msgStr.size() - 1; // 如果是奇数 -1
oddflag = 1;
}
for (int i=0; i<msgSize; i+=2) //不管奇数偶数,先处理前面偶数个字节
{
uint8_t index=(i/16.0)*8;
int chex1 = chartoHex(msgStr[i].toLatin1());
int chex2 = chartoHex(msgStr[i+1].toLatin1());
canData[index] = chex1*16+chex2;
}
if(oddflag==1) //奇数,剩下最后一个字节处理
{
uint8_t index=(msgStr.size()/16.0)*8;
int chex1 = chartoHex(msgStr[msgStr.size()-1].toLatin1());
canData[index] = chex1;
}
VCI_CAN_OBJ CANmsg;
CANmsg.ID = sfid;
CANmsg.SendType = 0;// 正常发送
CANmsg.RemoteFlag = 0;// 数据帧
CANmsg.ExternFlag = 0;// 标准帧
CANmsg.DataLen = 8;// 数据长度1个字节
for(int j=0; j<8; j++)
{
CANmsg.Data[j] = canData[j];
}
VCI_Transmit(canDevicrType,canDevicrInd,0, &CANmsg, 1);
}
09-08
5281
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-11
5839
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)