使用cubitruck上的c++发送at命令

sending at commands with c++ on cubietruck

本文关键字:at 命令 发送 c++ cubitruck 上的 使用      更新时间:2023-10-16

我有cubibard3(cubitruck),我正试图从cb向调制解调器发送AT命令,但我一直在读取调制解调器的答案。这是我的C++代码:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
using namespace std;

int main(void)
{
  int fd; /* file descryptor for port */
  fd = open("/dev/ttyS1", O_RDWR | O_NOCTTY | O_NDELAY);
  if (fd == -1)//if could not open the port
  {
    perror("open_port: Unable to open /dev/ttyS1 - ");
  }
  else //if port opened
  {
    fcntl(fd, F_SETFL, FNDELAY);
      //sending data
    std::cout<<"Port opened!"<<endl;
    std::cout<<"Sending 'ATZr' "<<endl;
    int n = write(fd, "ATZr", 4);
    if (n < 0)
      fputs("write() of 4 bytes failed!n", stderr);
    else std::cout<<"Data send!"<<endl;
    //reading data
    char buf [10];
    int f = read(fd, buf, sizeof(buf));
    if (f < 0) fputs("Reading failed!n", stderr);
    else std::cout<<f<<endl;
  }
  return (fd);
}

它还给我:

Port opened!
Sending ATZ
Data send!
Reading failed!

我做错了什么?

我更改了fcntl(fd,F_SETFL,FNDELAY);到fcntl(fd,F_SETFL,0);它开始正确地阅读,但它开始发送某种垃圾来寻找答案。

阅读您的代码时,我没有看到任何奇怪的事情(除了返回fd,但这与任何调制解调器行为无关)。在我的机器上测试代码时,它工作得很好,尽管我用AT而不是ATZ进行了测试,读取结果返回0,因为程序太快,并且在调制解调器提供响应之前尝试读取。注释掉fcntl调用会使程序读取6个字节。

为了进一步调试,你可以尝试用AT而不是ATZ运行,看看这是否有什么不同,因为ATZ会进行一些重置和清除,所以可能会有一些副作用导致你的问题,这不是不可想象的(尽管我认为这不太可能。但测试起来很简单,应该将其作为可能的原因排除)。

然而,我并不是为了抢你写串行通信程序的乐趣,我要指出的是,我已经写了一个名为atinout的程序,它已经实现了你试图用你的程序实现的目标。Atinout用于命令行调用,如下所示:

$ echo ATZ | atinout - /dev/ttyS1 -
ATZ
OK
$