0

我正在尝试使用串行通信向设备发送一些数据:

void VcpBridge::write_speed(char address, int spd) {
    uint8_t speed = (uint8_t)(127);
    ROS_ERROR("VCP BRIDGE: Sending %u to %u", speed, address);
    char msg[8];
    char command = 0x55, size = 0x02, csum;
    csum = speed + 0x64 + address;
    sprintf(msg, "%c%c%c%c%c%c", command, address, speed, size, 0x64, csum);
    ROS_ERROR(msg);
    write(fd_, msg, 6);
}

ROS_ERROR这里与printf.

一切正常,除非值speed超过 127。然后它总是?在它的位置打印 a 并且设备没有接收到正确的信息。你知道有什么方法可以正确投射吗?我试过%u了,但是程序崩溃了。

4

2 回答 2

2

sprintf在您的示例中没有充分的理由使用。试试这个:

void VcpBridge::write_speed(char address, int spd) {
    uint8_t speed = (uint8_t)(127);
    ROS_ERROR("VCP BRIDGE: Sending %u to %u", speed, address);
    char command = 0x55, size = 0x02, csum;
    csum = speed + 0x64 + address;
    ROS_ERROR(msg);
    char msg[] = { command, address, speed, size, 0x64, csum};
    write(fd_, msg, sizeof msg);
}
于 2012-07-03T19:45:15.863 回答
0

感谢您的回答,我可以找出解决问题的方法。不使用 sprintf 和使用 unsigned int 是关键。这是最终代码:

void VcpBridge::write_speed(char address,int spd){
  uint8_t speed = (uint8_t)(200);
  unsigned char command = 0x55, size=0x02, csum;
  csum=speed+0x64+address;
  unsigned char msg[8]= { command, address, speed, size, 0x64, csum };
  write( fd_, msg, 6);
}
于 2012-07-03T20:01:06.027 回答