UbuntuでLibSerialを使用して、シリアルポートでデータの読み取りと書き込みを行っています。
現時点では、シリアルポートを介して文字列を読み書きすることはできますが、コードがうまく機能していません。特に、何か読むものがある場合にのみ読み取るように、読み取り機能を制御したいと思います。フロープログラムをブロックせずに別のコマンドを送信するために読み取る情報がない場合は終了します。
私はやってみたいです:
- コマンドを書く
- 答えを待つ
- 次に、別のコマンドを記述します
- 答えを待つ
これで、whileループでread関数を使用して最初のコマンドを送信し、回答を読み取ることができますが、それ以外のことはできません。 whileループが終了せず、プログラムが読み取りを続行するため、2番目のコマンドを送信できません。
手伝ってくれませんか。
これは私が使用しているコードです:(読み取りおよび書き込み機能はコードの最後にあります)
#include <SerialStream.h>
#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <string>
int
main( int argc,
char** argv )
{
//
// Open the serial port.
//
using namespace std;
using namespace LibSerial ;
SerialStream serial_port ;
char c;
serial_port.Open( "/dev/ttyACM0" ) ;
if ( ! serial_port.good() )
{
std::cerr << "[" << __FILE__ << ":" << __LINE__ << "] "
<< "Error: Could not open serial port."
<< std::endl ;
exit(1) ;
}
//
// Set the baud rate of the serial port.
//
serial_port.SetBaudRate( SerialStreamBuf::BAUD_9600 ) ;
if ( ! serial_port.good() )
{
std::cerr << "Error: Could not set the baud rate." <<
std::endl ;
exit(1) ;
}
//
// Set the number of data bits.
//
serial_port.SetCharSize( SerialStreamBuf::CHAR_SIZE_8 ) ;
if ( ! serial_port.good() )
{
std::cerr << "Error: Could not set the character size." <<
std::endl ;
exit(1) ;
}
//
// Disable parity.
//
serial_port.SetParity( SerialStreamBuf::PARITY_NONE ) ;
if ( ! serial_port.good() )
{
std::cerr << "Error: Could not disable the parity." <<
std::endl ;
exit(1) ;
}
//
// Set the number of stop bits.
//
serial_port.SetNumOfStopBits( 1 ) ;
if ( ! serial_port.good() )
{
std::cerr << "Error: Could not set the number of stop bits."
<< std::endl ;
exit(1) ;
}
//
// Turn off hardware flow control.
//
serial_port.SetFlowControl( SerialStreamBuf::FLOW_CONTROL_NONE ) ;
if ( ! serial_port.good() )
{
std::cerr << "Error: Could not use hardware flow control."
<< std::endl ;
exit(1) ;
}
//
// Do not skip whitespace characters while reading from the
// serial port.
//
// serial_port.unsetf( std::ios_base::skipws ) ;
//
// Wait for some data to be available at the serial port.
//
//
// Keep reading data from serial port and print it to the screen.
//
// Wait for some data to be available at the serial port.
//
while( serial_port.rdbuf()->in_avail() == 0 )
{
usleep(100) ;
}
char out_buf[] = "check";
serial_port.write(out_buf, 5); <-- FIRST COMMAND
while( 1 )
{
char next_byte;
serial_port.get(next_byte); HERE I RECEIVE THE FIRST ANSWER
std::cerr << next_byte;
}
std::cerr << std::endl ;
return EXIT_SUCCESS ;
}