Linux串口:输入中缺少数据

时间:2016-08-04 13:09:07

标签: c++ linux arduino serial-port uart

    #include <fcntl.h>   
    #include <termios.h> 
    #include <unistd.h>  
    #include <errno.h>   
    #include <cerrno>
    #include <iostream>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <fstream>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <cstdlib>
    #include <ctime>

    using namespace std;
    typedef struct termios ComSet;

    int main()
    {
    int acm=-1;                                   
    acm=open("/dev/ttyACM0",O_RDWR | O_NOCTTY);
    if(acm == -1)
    {
    cout<<"Error Opening ttyACM0"<<endl;
    exit(1);
    }
    else
    {
    cout<<"Preparing ttyACM0..."<<endl;
    ComSet SerialSettings;
    tcgetattr(acm, &SerialSettings);
    cfsetispeed(&SerialSettings,B9600);
    cfsetospeed(&SerialSettings,B9600);

 /* 8N1 Mode */
    SerialSettings.c_cflag &= ~PARENB;   
    SerialSettings.c_cflag &= ~CSTOPB;   
    SerialSettings.c_cflag &= ~CSIZE;   
    SerialSettings.c_cflag |=  CS8;     

    SerialSettings.c_cflag &= ~CRTSCTS;       
    SerialSettings.c_cflag |= CREAD | CLOCAL; 


    SerialSettings.c_iflag &= ~(IXON | IXOFF | IXANY);          
    SerialSettings.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG);  
    SerialSettings.c_oflag &= ~OPOST;                           

 /* Setting Time outs */
    SerialSettings.c_cc[VMIN]  = 10;     /* Read at least 10 characters */
    SerialSettings.c_cc[VTIME] = 0;     /* Wait indefinetly   */

    if((tcsetattr(acm,TCSANOW,&SerialSettings)) != 0)   
    {
        cout<< " ERROR ! in Setting attributes"<<endl;

    }
    else
    {
        cout<< "=======ttyACM0 Setting====="<<endl;
        cout<<"BaudRate = 9600 StopBits = 1 Parity = none"<<endl;
        cout<<"Reading ttyACM0... "<<endl;
        char read_buffer[1024];                                
        bzero(read_buffer,1024);
        int read_bytes=0;                                      
        while(1)
         {
                tcflush(acm, TCIFLUSH);                        
                read_bytes=read(acm,&read_buffer,1024);        
                if(read_bytes>0)
                {
                    cout<<read_buffer;
                    bzero(read_buffer,1024);
                }

         }
    }



  close(acm); /* Close the serial port */

}

return 0;
}

由于某种原因代码它不能正常工作我试图从arduino读取因为它正在更早地工作它给我grabled输出 比如

世界! 你好,世界 ! ello World! llo世界! llo World!

改变的一件事是

终端输出中有一个额外的新行,这是使用cat / dev / ttyAMC0

Hello World!

Hello World!

Hello World!

Hello World!

Hello World!

我想逐行阅读,因为它是由arduino发送到终端

1 个答案:

答案 0 :(得分:1)

如果出现像lo World ! Hello World ! ello World !这样的乱码输出,则通常表示您的时钟速度(波特率)不匹配。确保您的Arduino以9600波特的速度写入。

此外,当Arduino输出字符时,它会将它们放入硬件缓冲区。 read()函数获取您指定的缓冲区的字节数 - 在本例中为1024.但您可能不希望每次都读取1024个字节。相反,我认为你应该阅读,直到你到达换行符。查看您正在使用的库中是否有readline()函数。

Linux cat命令正在正确读取,但命令本身在最后添加了一个额外的换行符。