我希望能够用C/C++代码从Linux的串口读取数据。
由于我仍然可以使用GtkTerm甚至使用
看起来串口没有正确初始化,因为在使用类似gtkterm的程序之后,读取操作就可以正常工作了。
以下是我用于初始化串口的代码(第二个版本):
注意:此代码是在您的评论下完成的第二个版本。
cat /dev/ttyUSB0
从该串口读取数据,因此这不是硬件/驱动程序问题。看起来串口没有正确初始化,因为在使用类似gtkterm的程序之后,读取操作就可以正常工作了。
以下是我用于初始化串口的代码(第二个版本):
UbiDriver::UbiDriver(const std::string &ttyPort)
{
// Doc : http://www.easysw.com/~mike/serial/serial.html#2_4
m_serialHandle = open(ttyPort.c_str(), O_RDWR | O_NOCTTY | O_NDELAY); // Open perif
if(m_serialHandle < 0)
{
MY_THROW("Impossible d'ouvrir le port '" << ttyPort << "' !\nerrno = " << errno);
}
// Conf
//if(fcntl(m_serialHandle, F_SETFL, 0) == -1) // lecture en mode bloquant
if(fcntl(m_serialHandle, F_SETFL, O_NONBLOCK) == -1) // lecture en mode non bloquant
{
MY_THROW("fcntl failed !\nerrno = " << errno);
}
struct termios options;
tcgetattr(m_serialHandle, &options); // Init struct avec la conf actuelle
cfsetispeed(&options, B9600); // In speed
cfsetospeed(&options, B9600); // Output speed
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_cflag |= (CLOCAL | CREAD); // Enable the receiver and set local mode...
options.c_cflag &= ~PARENB; // Desactive bit de parité
options.c_cflag &= ~CSTOPB; // Désactive 2 stop bits -> Active 1 stop bits
options.c_cflag &= ~CSIZE; // Désactive le bit "CSIZE"
options.c_cflag |= CS8; // Communication sur 8 bits
options.c_oflag &= ~OPOST; // Raw output is selected by resetting the OPOST option in the c_oflag member:
// Application de la conf
if(tcsetattr(m_serialHandle, TCSAFLUSH, &options) == -1) // Vidage buffer & application immédiate
{
MY_THROW("tcsetattr failed !\nerrno = " << errno);
}
}
读取端口数据
std::string UbiDriver::GetAnswer()
{
const int buffSize = 1024;
char buffer[buffSize] = {'\0'};
int count = 0;
std::string wholeAnswer = "";
int noDataTime = 0;
while(noDataTime < 2) // Tant qu'il y a des données à lire
{
count = read(m_serialHandle, buffer, buffSize - 1);
if(count == -1)
{
MY_THROW("Impossible de lire sur le port serie. Verifiez la connexion avec l'imprimante !")
}
if(count > 0)
{
noDataTime = 0;
buffer[count] = '\0';
for(int i = 0; i < count; i++)
{
buffer[i] &= ~128; // Supression du premier 1 du binaire
}
wholeAnswer += std::string(buffer);
std::cout << count << std::endl;
}
else
{
noDataTime++;
usleep(100000);
}
}
cerr << "----------- Answer -----------" << endl;
cerr << "Size = " << wholeAnswer.size() << endl;
cerr << wholeAnswer << endl;
return wholeAnswer;
return std::string("");
}
注意:此代码是在您的评论下完成的第二个版本。