c++ - 无法打开 UART。确保它没有被其他应用程序使用

标签 c++ c serial-port raspberry-pi uart

我在处理 Raspberry Pi 上的 UART 时遇到了一个奇怪的问题。问题很简单,我初始化UART如图here并将波特率设置为 9600,甚至前几个字节的传输也能顺利进行。然而,一段时间后,当我不断地发送数据时,树莓派在屏幕上显示这条消息:无法打开 UART。确保它未被其他应用程序使用。

我不知道我哪里出错了,让事情变得更复杂,我前几天遇到了这个问题,之前代码运行很长时间没有错误。

这是代码片段:

    minMaxLoc( diffImg, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );
    xpos=maxLoc.x;
    ypos=maxLoc.y;

    xposs = xpos - xposp;
    yposs = ypos - yposp;
    xposp = xpos;
    yposp = ypos;
    char x_tx_buffer[20], y_tx_buffer[20];
    char x_dummy_buffer[20];
    char y_dummy_buffer[20];
    char *p_x_tx_buffer, *p_y_tx_buffer;

    sprintf(x_dummy_buffer,"%d", (int)(abs(xposs*2.5)));
    sprintf(y_dummy_buffer,"%d", (int)(abs(yposs*2.5)));

    p_x_tx_buffer = &x_tx_buffer[0];
    *p_x_tx_buffer++ = x_dummy_buffer[0];
    *p_x_tx_buffer++ = x_dummy_buffer[1];
    *p_x_tx_buffer++ = x_dummy_buffer[2];
    *p_x_tx_buffer++ = x_dummy_buffer[3];

    p_y_tx_buffer = &y_tx_buffer[0];
    *p_y_tx_buffer++ = y_dummy_buffer[0];
    *p_y_tx_buffer++ = y_dummy_buffer[1];
    *p_y_tx_buffer++ = y_dummy_buffer[2];
    *p_y_tx_buffer++ = y_dummy_buffer[3];

    uart0_filestream = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY);      //Open in non blocking read/write mode
    if (uart0_filestream == -1)
    {
        //ERROR - CAN'T OPEN SERIAL PORT
        printf("Error - Unable to open UART.  Ensure it is not in use by another application\n");
    }
    if (uart0_filestream != -1)
    {
        int countx = write(uart0_filestream, &x_tx_buffer[0], (p_x_tx_buffer - &x_tx_buffer[0]));       //Filestream, bytes to write, number of bytes to write
        int county = write(uart0_filestream, &y_tx_buffer[0], (p_y_tx_buffer - &y_tx_buffer[0]));       //Filestream, bytes to write, number of bytes to write
        if (countx < 0 || county < 0)
        {
            printf("UART TX error\n");
        }
    }

我哪里错了?

最佳答案

您需要在例程结束时执行此操作。

close(uart0_filestream);

关于c++ - 无法打开 UART。确保它没有被其他应用程序使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18088250/

相关文章:

c++ - 为什么 ADL 不适用于 Boost.Range?

清除串口缓冲区

c++ - 如何使用 boost::asio 正确编写 Win32 应用程序以通过串行连接进行通信

c++ - 为什么 HID 在 mac 中枚举 Apple Internal Keyboard/Trackpad 3 次?

c++ - 为什么 std::atomic<bool> 比 volatile bool 慢得多?

c - Libnet TCP 校验和错误

c - vfscanf.c 没有那个文件或目录

c++ - 检测对范围外变量的访问

c - “BMSerial”未命名类型

c++ - 如果输入非整数,如何防止无限循环?