![내 GSM 모뎀이 mini2440의 명령을 반영합니다.](https://linux55.com/image/77063/%EB%82%B4%20GSM%20%EB%AA%A8%EB%8E%80%EC%9D%B4%20mini2440%EC%9D%98%20%EB%AA%85%EB%A0%B9%EC%9D%84%20%EB%B0%98%EC%98%81%ED%95%A9%EB%8B%88%EB%8B%A4..png)
USB 직렬 포트(ttyUSB0)를 통해 mini2440과 GSM 모뎀이 서로 연결되어 있습니다. 이것은 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만 씁니다. 아니요, 하지만 my (if(s.find("OK")))는 true를 반환합니다. 그러면 어떻게 되나요? AT가 에코되는 이유는 무엇입니까?