我有 mini2440 和 GSM 调制解调器,它们通过 USB 串行端口(ttyUSB0)相互连接。这是我用 C++ 发送 AT 的代码:
#include <QCoreApplication>
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <string> /*To use string type*/
#include <iostream>
#include <string>
using namespace std;
// Definations
int fd; /* File descriptor for the port */
string wr;
int rd;
char buffer[100]; /* Input buffer */
int openport(void);
void closeport(void);
void configport(void);
string WriteRead(void);
//-------------------------------------
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
openport();
if(fd>-1)
{
configport();
string str=WriteRead();
qDebug(str.c_str());
}
return a.exec();
}
//-------------------------------------
int openport(void)
{
fd=open("/dev/ttyUSB0",O_RDWR|O_NOCTTY|O_NDELAY);
if (fd==-1)
{
perror("open_port: unable to open port /dev/ttyUSB0\n");
return -1;
}
else
{
printf("open_port: succesfully open port /dev/ttyUSB0\n");
fcntl(fd,F_SETFL,0);
return 1;
}
}
//-------------------------------------
void closeport(void)
{
close(fd);
}
//-------------------------------------
void configport(void)
{
struct termios options;
tcgetattr(fd,&options);
cfsetispeed(&options,B9600);
cfsetospeed(&options,B9600);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~ PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_iflag &= ~(IXON|IXOFF|IXANY);
tcsetattr(fd,TCSANOW,&options);
}
//------------------------------------
string WriteRead(void)
{
char buffer[255]; /* Input buffer */
char *bufptr; /* Current char in buffer */
int nbytes; /* Number of bytes read */
int tries; /* Number of tries so far */
for (tries = 0; tries < 3; tries ++)
{
if (write(fd, "AT\r", 3) < 3)// send an AT command followed by a CR
continue;
// read characters into our string buffer until we get a CR or NL
bufptr = buffer;
while ((nbytes = read(fd, bufptr, buffer + sizeof(buffer) - bufptr
- 1)) > 0)
{
bufptr += nbytes;
if (bufptr[-1] == '\n' || bufptr[-1] == '\r')
break;
}
/* nul terminate the string and see if we got an OK response */
*bufptr = '\0';
string s(buffer);
if (s.find("OK"))
{
return s;
}
else
return "not answer";
}
}
但在发送 AT 之后,我说如果找到“OK”,则将缓冲区设置为字符串 s。然后在输出中写入字符串 s 。但它只写AT。没有 OK,但我的 (if(s.find("OK"))) 返回 true。那么会发生什么呢?为什么回显AT?