无法打开UART。确保其他应用程序未使用它

时间:2013-08-06 18:53:58

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

在Raspberry Pi上处理UART时遇到了一个奇怪的问题。问题很简单,我将UART初始化为here,并将波特率设置为9600,甚至前几个字节的传输也很顺利。但是,在我不断发送数据的某个时间之后,RPi会在屏幕上显示此消息:无法打开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");
        }
    }

我哪里错了?

1 个答案:

答案 0 :(得分:2)

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

close(uart0_filestream);