簡體   English   中英

如何將uint8_t放在char數組中?

[英]How to put a uint8_t in a char array?

我正在嘗試使用串行通信將一些數據發送到設備:

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.那么它總是會打印一個? 在它的位置,設備沒有收到正確的信息。 你知道如何正確地投射嗎? 我已經嘗試了%u但程序崩潰了。

在您的示例中沒有充分的理由使用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);
}

感謝您的回答,我可以找出解決問題的熱點。 不使用sprintf並使用unsigned int是kay.There是最終代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM