【问题标题】:How to send an array of bytes between nucleo f446re with mbed through USB with UARTSerial class?如何通过带有UARTSerial类的USB在带有mbed的nucleo f446re之间发送字节数组?
【发布时间】:2019-11-18 01:02:01
【问题描述】:

我必须使用 UARTSerial 类在 nucleo f446re 和带有 ubuntu 的 pc 之间发送数据数组。

我在 mbed 上使用的代码如下:

int main() {
    UARTSerial pc(USBTX, USBRX, 921600);
    uint8_t buff[256] = {
        5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4
    };

    pc.sync();

    while(true) {
        pc.write(buff, 23);
        pc.sync();
        wait(1);
    }

    return 0;
}

我在电脑上运行的代码是:

int main() {
    struct termios tattr{0};

    // open the device in read/write sync
    int com = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_SYNC );

    if (com == -1)
        throw std::runtime_error("ERROR: can't open the serial");

    tcgetattr(com, &tattr);

    tattr.c_iflag &= ~(INLCR|IGNCR|ICRNL|IXON);

    tattr.c_oflag &= ~(OPOST|ONLCR|OCRNL|ONLRET); 

    tattr.c_cflag = CS8 | CREAD | CLOCAL; 

    tattr.c_lflag &= ~(ICANON|ECHO);    

    tattr.c_cc[VMIN] = 1;

    tattr.c_cc[VTIME] = 0;

    tattr.c_ispeed = 921600;
    tattr.c_ospeed = 921600;

    tcsetattr (com, TCSAFLUSH, &tattr);

    while (true) {
        usleep(1000);
        tcflush(com, TCIOFLUSH);
        uint8_t buff[24];
        ::read(com, buff, 23);

        printf("reading frame... ");
        for (auto b : buff) {
            printf("%02X ", b);
        }
        puts("\n");
    }
}

我在电脑上收到的输出是:

[...]
reading frame... 00 00 8D 9C 1E 7F 00 00 00 00 00 00 00 00 00 00 70 5B C7 01 AD 55 00 00 

reading frame... 00 00 8D 9C 1E 7F 00 00 00 00 00 00 00 00 00 00 70 5B C7 01 AD 55 00 00  
[...]

如您所见,结果与我预期的不一样。

我已经尝试使用循环一次发送一个字节,但结果是一样的。

我不明白为什么我无法读取我尝试在 pc 和核板上刷新 USB 的 USB。

【问题讨论】:

    标签: c++ uart mbed nucleo


    【解决方案1】:

    您必须使用解码器来解码来自串行端口的字节 请参阅下面的链接: https://codereview.stackexchange.com/questions/200846/a-simple-and-efficient-packet-frame-encoder-decoder

    【讨论】:

    • 我不明白为什么我必须使用解码器而不使用任何协议来发送数据。
    • 事实上,从串口读取时,它只是咬,因为它在发送数据时转换为字节,所以要获得人类可读的信息,你应该解码这些数据。
    【解决方案2】:

    我发现了问题。这是波特率的设置,我必须使用这行:

    // receive speed
    cfsetispeed (&tattr, B921600);
    // transmit speed
    cfsetospeed (&tattr, B921600);
    

    而不是这个:

    // receive speed
    tattr.c_ispeed = 921600;
    tattr.c_ospeed = 921600;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-19
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 2017-01-21
      • 2012-05-12
      • 1970-01-01
      • 2015-08-20
      相关资源
      最近更新 更多