通过串口发送数据

问题描述

我正在尝试以编程方式通过串行端口发送数据。我有一个运行 Linux 的嵌入式系统。在引导加载程序提示符下,我打算通过按 CTRL+C 并修改引导参数来停止执行。我可以发送 CTRL+C 字符并且启动会停止。但是,当我尝试使用 write() 通过串行端口发送一个大命令时,它似乎没有成功。关于什么可能是错误的任何输入?下面是我的代码片段:

int main() {
  // Open the serial port. Change device path as needed (currently set to an standard FTDI USB-UART cable type device)
  int serial_port = open("/dev/ttyUSB0",O_RDWR);

  // Create new termios struc,we call it 'tty' for convention
  struct termios tty;
  char data = 0x03; 
  char data2[]={'r','u','n',' ','l','o','a','d','b','t','e','v','\r'};
  char data4[]= "setenv mmcargs \'setenv bootargs console=ttyO0,115200n8 console=tty0 ${optargs} 
  root=/dev/mmcblk1p3 rootfstype=ext4 panic=1\';

  // Read in existing settings,and handle any error
  if(tcgetattr(serial_port,&tty) != 0) {
      printf("Error %i from tcgetattr: %s\n",errno,strerror(errno));
      return 1;
  }

  tty.c_cflag  = CS8 | CLOCAL | CREAD;
  tty.c_iflag = IGNBRK | IGNPAR;
  tty.c_oflag = OPOST;
  tty.c_lflag = 0;
  tty.c_cc[VMIN] = 1;
  tty.c_cc[VTIME] = 0;
  tcflush(serial_port,TCIFLUSH);

  // Set in/out baud rate to be 115200
  cfsetispeed(&tty,B115200);
  cfsetospeed(&tty,B115200);

  // Save tty settings,also checking for error
  if (tcsetattr(serial_port,TCSANow,&tty) != 0) {
      printf("Error %i from tcsetattr: %s\n",strerror(errno));
      return 1;
  }

   write(serial_port,&data,1);
   ret = write(serial_port,&data2,sizeof(data2));
   ret = write(serial_port,&data4,sizeof(data4));

所有写入都成功(我通过返回值验证了这一点)但随后对应于 data4 的写入未成功生成响应。当我同时运行 minicom 时,我看到实际上只写入了最终写入的 27 个字节。不知道哪里出了问题。

如果我使用 putty 给出与 data4 中相同的命令,它会成功而没有任何问题。腻子上的设置是速度(波特):115200 数据位:8 停止位:1 奇偶校验:无 流量控制:无

有人可以帮助我哪里出错了吗? 谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)