简体   繁体   English

可用数据时从串行端口读取

[英]Read from serial port when data available

I'm trying to write a program that communicates with serial port which is connected to GSM modem. 我正在尝试编写一个程序,该程序与连接到GSM调制解调器的串行端口通信。 Using AT command to communicate with modem. 使用AT命令与调制解调器通信。 Here's my code. 这是我的代码。 Got it from http://tldp.org/HOWTO/Serial-Programming-HOWTO/x115.html - Canonical Input Processing. http://tldp.org/HOWTO/Serial-Programming-HOWTO/x115.html-规范输入处理中获得了它。

It works fine when output returns single line. 当输出返回单行时,它工作正常。 For example: 例如:

AT returns OK AT返回OK

And my problem is If i send AT+CPIN? 我的问题是,如果我发送AT+CPIN? which returns several lines for example: 例如,它返回几行:
+CPIN: SIM PIN
OK

but my program reads only +CPIN: SIM PIN and breaks.How to fix it ? 但是我的程序只读取+CPIN: SIM PIN并中断。如何解决?

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

#define BAUDRATE B38400            
#define dev "/dev/ttyUSB0"
#define _POSIX_SOURCE 1

#define FALSE 0
#define TRUE 1

volatile int STOP=FALSE; 

main()
{
  char pinn[20];
  char buf[255];
  int fd,res=0;
  printf("%s\n", dev);
  struct termios oldtio,newtio;
  fd = open(dev, O_RDWR | O_NOCTTY ); 
  if (fd <0) {perror(dev); exit(-1); }
  bzero(&newtio, sizeof(newtio));
  newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
  newtio.c_iflag = IGNPAR | ICRNL;
  newtio.c_oflag = 0;
  newtio.c_lflag = ICANON;
  newtio.c_cc[VMIN]     = 1;
  tcflush(fd, TCIFLUSH);
  tcsetattr(fd,TCSANOW,&newtio);


  if (fd < 0)
  {
      printf("Error opening serial port\n");
      exit(1);
  }
  while(1){

    scanf("%s",pinn);
    strcat(pinn,"\r");

    if (write(fd, pinn, strlen(pinn)) < strlen(pinn)) printf("Write error - %s \n", strerror(errno));
    pinn[strlen(pinn)-1]=0;
    while(1){
      res = read(fd,buf,255);
      buf[res]=0;
      buf[res-1]=0;
      if (res>1&&NULL==strstr(buf,pinn)) break;
    }
    printf("\"%s\"\n", buf);
  }
  close(fd);
}

code UPDATE removed duplicate read 代码更新删除重复读取

Besides other minor deficiencies of the code, your receiving while() loop will terminate if the returned string does not contain the command you initially sent (NULL==strstr(buff, pinn)) . 除了代码的其他一些小缺陷外,如果返回的字符串不包含您最初发送的命令(NULL==strstr(buff, pinn)) ,则您的while()循环将终止。

This condition is obviously not met when you receive multiline results (as only the first line contains the AT command you sent). 当您收到多行结果时,显然不满足此条件(因为只有第一行包含您发送的AT命令)。

You need to change that if you don't want it. 如果您不想要,则需要更改它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM