【问题标题】:termios Arduino read/write failingtermios Arduino 读/写失败
【发布时间】:2013-05-18 21:44:57
【问题描述】:

您好,我在尝试对 Arduino 进行编程以从 c++ 程序中获取命令时遇到了一些麻烦。我正在使用 termios 连接到 Arduino。 Arduino 处于网关模式(基本上它本身并不执行代码,而是等待来自我的程序的输入与我连接到它的硬件进行交互)。

我的 termios 设置是这样的:

SerialHandler::SerialHandler(char* fPath, int bRate)
{
filePath = fPath;
baudRate = 0;

//Open the file, file is of type int
file = open(filePath, O_RDWR | O_NOCTTY);
if(file<0) //If there is an error opening the file
{
    perror(filePath);
    exit(-1);
}
//Save the old port settings
tcgetattr(file, &oldtio);
bzero(&newtio, sizeof(newtio));
//now to load the baudrate
getBaudRate(bRate, baudRate);
newtio.c_cflag = baudRate | CRTSCTS | CS8 | CLOCAL | CREAD;

//IGNPAR ignore bits with parity errors
//ICRNL  map CR to NL ..May have to change to raw input processing
newtio.c_iflag = IGNPAR;

//Raw output
newtio.c_oflag = 0;

//ICANON - enable canonical input
//disables echo functionality, doesnt send signals to calling program
newtio.c_lflag = ICANON;

//Clean and activate port
tcflush(file, TCIFLUSH);
tcsetattr(file, TCSANOW, &newtio);
}

我的 Arduino 读写代码是这样的:

void SerialHandler::getSerialOutput(char* readBuffer, int& bufferPoint)
{
cout <<"Beginning read\n";


bufferPointer = read(file, outputBuffer,255);
cout <<"Finished Read\n";
for(int i=0;i<bufferPointer;i++)
{
    cout << outputBuffer[i]<<endl;
    readBuffer[i] = outputBuffer[i];
}
bufferPoint = bufferPointer;
}


void SerialHandler::writeSerial(char* writeBuffer, int length)
{
cout << "Writing: " << writeBuffer<<endl;
write(file,writeBuffer,length);
cout << "Finished Write \n";
}

最初我向 Arduino 发送一个测试命令 ("AT\r\n"),它以 ("OK") 响应,但在此之后任何后续读/写都失败了。

在测试命令中,Arduino 的 RX 和 TX 引脚会亮起(意味着它正在接收和传输数据),但之后我发送的命令失败。当我尝试写入时,Arduino 不亮,任何读取命令都会无限期挂起。

我认为问题类似于文件处理程序关闭,但我不确定如何测试它,否则可能完全是另一个问题。

【问题讨论】:

  • 始终检查write()的返回值,处理部分写入。
  • 嗨,您的意思是将返回值分配给 int 吗?我刚刚尝试过,结果是 4 用于有效的命令,而 10 用于其他命令。这是有道理的,因为第一个命令是 4 个字符长,第二个是 10 个字符,但程序实际上仍然没有将命令写入 Arduino。
  • 似乎是波特率问题。你如何获得波特率信息?你知道波特率参数需要是BXXXX 常量之一并且不是任意的吗?
  • 是的,getBaudRate() 方法从传入的 bRate 中找出所需的波特率,然后将变量 baudRate 设置为正确的 BXXXX。

标签: c++ serial-port arduino termios


【解决方案1】:

尝试从 newtio.c_cflag 行中删除 CRTSCTS。当您连接串行连接的所有电缆时,需要 CRTSCTS。使用 Arduino 时,您只连接 tx rx 和 gnd 线。有关更多信息,请参阅 termios 手册页http://linux.die.net/man/3/termios

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    相关资源
    最近更新 更多