Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

c - Sending data over serial port

I am trying to send data over serial port programmatically. I have an embedded system which runs Linux. On the bootloader prompt, I intend to stop execution by pressing CTRL+C and modifying the boot args. I am able to send the CTRL+C character and the booting does stop. However when I try to send a big command over serial port using the write(), it doesn't seem to be succeeding. Any inputs on what could be wrong? Below is my code snippet:

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','o','o','t','e','n','v','
'};
  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
", 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
", errno, strerror(errno));
      return 1;
  }

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

All the writes succeed (this i verified by returned value) but then the write corresponding to data4 doesn't succeed in generating a response. When I simultaneously run minicom, I see that only 27 bytes of the final write are actually written. Not sure what is wrong.

If I give the same command as in data4 using putty, it succeeds without any issue. The settings on putty were speed(baud): 115200 Databits: 8 Stopbits: 1 Parity: NONE Flowcontrol: NONE

Can someone help me where I am going wrong? Thanks!

question from:https://stackoverflow.com/questions/65949710/sending-data-over-serial-port

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...