【问题标题】:C++ not writing whole data to UART portC ++没有将整个数据写入UART端口
【发布时间】:2021-06-05 13:40:20
【问题描述】:

我一直在用 WiringPi 在 C++ 中测试 UART 通信。

问题:

C++ 似乎没有将整个数据输出到 UART 端口/dev/ttyAMA0。也许我做错了?

调查

注意:我正在使用 minicomminicom --baudrate 57600 --noinit --displayhex --device /dev/ttyAMA0 来检查接收到的数据。

还有! UART 端口、RXTX 引脚短接在一起。

python 代码运行良好,但是当我尝试在 C++ 中实现它时,收到的数据不同。

预期收到的数据应该是:ef 01 ff ff ff ff 01 00 07 13 00 00 00 00 00 1b

接收数据比较:

Language Used Data Received from Minicom
Python ef 01 ff ff ff ff 01 00 07 13 00 00 00 00 00 1b
C++ ef 01 ff ff ff ff 01

使用的代码

Python:

import serial
from time import sleep

uart = serial.Serial("/dev/ttyAMA0", baudrate=57600, timeout=1)

packet = [239, 1, 255, 255, 255, 255, 1, 0, 7, 19, 0, 0, 0, 0, 0, 27]

uart.write(bytearray(packet))

C++:

注意:使用g++ -Wall -O3 -o test hello.cpp -lwiringPi编译的代码

#include <iostream>
#include <string.h>
#include <wiringPi.h>
#include <wiringSerial.h>

using namespace std;

int main()
{

      int serial_port;

      if (wiringPiSetup() == -1)
            exit(1);

      if ((serial_port = serialOpen("/dev/ttyAMA0", 57600)) < 0)
      {
            fprintf(stderr, "Unable to open serial device: %s\n", strerror(errno));
            return 1;
      }

      cout << "Sending data to UART" << std::endl;

      serialPuts(serial_port, "\xef\x01\xff\xff\xff\xff\x01\x00\x07\x13\x00\x00\x00\x00\x00\x1b");

      return 0;
}

【问题讨论】:

    标签: c++ wiringpi


    【解决方案1】:

    您不能使用serialPuts 发送空终止符。与所有类似的函数一样,它会在字符串中遇到空终止符时停止。在这种情况下,我认为您最好的选择是添加一个函数,该函数使用 WiringPi 自己的函数在内部使用的普通 write 函数。

    您可以创建一个包装函数,使其看起来与其他调用相似:

    #include <cstddef>
    
    void serialWrite(const int fd, const char* data, size_t length) {
        write(fd, data, length);
    }
    

    也许还有一个函数模板,不必手动计算固定数据数组中数据的长度:

    template<size_t N>
    void serialWrite(const int fd, const char(&data)[N], bool strip_last = true) {
        serialWrite(fd, data, N - strip_last);
    }
    

    您现在可以像这样使用它:

    serialWrite(serial_port, "\xef\x01\xff\xff\xff\xff\x01\x00\x07\x13\x00\x00\x00\x00\x00\x1b");
    

    注意:有一个 pull request 可以向 WiringPi 库添加一个类似的功能(称为 serialPut),如果您不想让您的自己的功能。

    【讨论】:

    • 成功了!不过,我花了一些时间重新编译整个库。非常感谢!
    • @Justsomesailboat 不客气!很高兴它成功了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多