通过串口读写二进制数据

时间:2012-07-25 12:39:04

标签: c linux file binary serial-port

所以我四处搜寻,无法找到我需要的东西。我需要帮助通过串口读取和写入二进制数据,并希望您有任何建议。请注意,当我处于这个项目的不同阶段时,我问了一个与之前类似的问题。

以下是计划。第一个程序打开一个文件“test.jpg”,以二进制模式读取它并将结果存储在缓冲区中。然后它关闭文件,并且应该通过串口发送该文件。

第二个程序创建一个名为“testout.jpg”的文件,并且应该读取从前一个程序发送的数据。

我有一种预感,我的代码中的问题在于第二个程序。也许我也需要使用fread呢?我试过,但我无法弄清楚如何为串口实现它,因为我对编程相对较新。

非常感谢你的时间。

串行写:

    #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 <stdlib.h>

    int main()
        {
                //writing
                int writeport = open_port("/dev/ttyUSB0");

                //open file

                FILE *file;
                char *buffer;
                int fileLen;

                file = fopen("test.jpg", "rb");

                //get file size

                fseek(file, 0, SEEK_END);
                fileLen = ftell(file);
                fseek(file, 0, SEEK_SET);

                buffer = (char *)malloc(fileLen + 1);

                //read file contents

                fread(buffer, fileLen, 1, file);
                fclose(file);

                int n = write(writeport, buffer, fileLen + 1);
                if (n < 0)
                        fputs("write() of bytes failed!\n", stderr);

                //closing ports
                close(writeport);
        }

        int open_port(char str[])
    {
        int fd = open(str, O_RDWR | O_NOCTTY | O_NONBLOCK); // ?? NDELAY or NONBLOCK?

      if (fd == -1)
      {
                        perror("open_port: Unable to open /dev/ttyS0 - ");
      }
      else
                        fcntl(fd, F_SETFL, 0);

          struct termios options;
          tcgetattr(fd, &options); //this gets the current options set for the port

          // setting the options

          cfsetispeed(&options, B9600); //input baudrate
          cfsetospeed(&options, B9600); // output baudrate
          options.c_cflag |= (CLOCAL | CREAD); // ?? enable receicer and set local mode
          //options.c_cflag &= ~CSIZE; /* mask the character size bits */
          options.c_cflag |= CS8;    /* select 8 data bits */
          options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // choosing raw input
          options.c_iflag &= ~INPCK; // disable parity check
          options.c_iflag &= ~(IXON | IXOFF | IXANY); // disable software flow control
          options.c_oflag |= OPOST; // ?? choosing processed output
          options.c_cc[VMIN] = 0; // Wait until x bytes read (blocks!)
          options.c_cc[VTIME] = 0; // Wait x * 0.1s for input (unblocks!)

          // settings for no parity bit
          options.c_cflag &= ~PARENB;
          options.c_cflag &= ~CSTOPB;
          options.c_cflag &= ~CSIZE;
          options.c_cflag |= CS8;

          tcsetattr(fd, TCSANOW, &options); //set the new options ... TCSANOW specifies all option changes to occur immediately

      return (fd);
    }

序列号阅读:

    #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 */

    int main()
        {
                //reading      
                int readport = open_port("/dev/ttyUSB1");

        //open resultant file

        FILE *file;
        //system("rm testout.jpg");
        file = fopen("testout.jpg", "wb");

                //trying to read one character at a time
                char buff;
                int n = 1;

           while (n > 0)
           {
                n = read(readport, &buff, 1);
                //printf("%c", buff, buff);

                **//I tried these three methods, with little success**

                //fprintf(file, "%c", buff);
                //fwrite(&buff, 1, 1, file);
                //write(file, &buff, 1);
           }

                //closing ports
                close(readport);
                fclose(file);
        }

        int open_port(char str[])
    {
        int fd = open(str, O_RDWR | O_NOCTTY | O_NONBLOCK); // ?? NDELAY or NONBLOCK?

      if (fd == -1)
      {
                        perror("open_port: Unable to open /dev/ttyS0 - ");
      }
      else
                        fcntl(fd, F_SETFL, 0);

          struct termios options;
          tcgetattr(fd, &options); //this gets the current options set for the port

          // setting the options

          cfsetispeed(&options, B9600); //input baudrate
          cfsetospeed(&options, B9600); // output baudrate
          options.c_cflag |= (CLOCAL | CREAD); // ?? enable receicer and set local mode
          //options.c_cflag &= ~CSIZE; /* mask the character size bits */
          options.c_cflag |= CS8;    /* select 8 data bits */
          options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // choosing raw input
          options.c_iflag &= ~INPCK; // disable parity check
          options.c_iflag &= ~(IXON | IXOFF | IXANY); // disable software flow control
          options.c_oflag |= OPOST; // ?? choosing processed output
          options.c_cc[VMIN] = 0; // Wait until x bytes read (blocks!)
          options.c_cc[VTIME] = 0; // Wait x * 0.1s for input (unblocks!)

          // settings for no parity bit
          options.c_cflag &= ~PARENB;
          options.c_cflag &= ~CSTOPB;
          options.c_cflag &= ~CSIZE;
          options.c_cflag |= CS8;

          tcsetattr(fd, TCSANOW, &options); //set the new options ... TCSANOW specifies all option changes to occur immediately

      return (fd);
    }

1 个答案:

答案 0 :(得分:1)

file = fopen( "zname.jpg", "wb" );
while (1) { 
  n = read(readport, &buff, 1);
  if (n == -1) switch(errno) {
         case EAGAIN: /* sleep() */ 
            continue;
          ...
         default: goto quit;
         }
  if (n ==0) break;
  fputc(buff, file);
  }
quit:
   fclose (file);
...

甚至比sleep()和循环更好,就是使用select / poll。 (你仍然需要检查EAGAIN)