Advertisement
milanmetal

[Linux/C] Read 10bytes from Serial Port

Feb 5th, 2018
384
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 8.42 KB | None | 0 0
  1.     /*=======================================================================*/
  2.         /* Serial Port Programming in C (Serial Port Read)                    */
  3.     /* Non Cannonical mode                                                      */
  4.     /* ----------------------------------------------------------------------*/
  5.         /* Program reads a string from the serial port at 9600 bps 8N1 format */
  6.     /* Baudrate - 9600                                                          */
  7.     /* Stop bits -1                                                             */
  8.     /* No Parity                                                                */
  9.     /* ----------------------------------------------------------------------*/
  10.     /* Compiler/IDE  : gcc 4.6.3                                                */
  11.     /* Library       :                                                          */
  12.     /* Commands      : gcc -o serialport_read serialport_read.c                 */
  13.     /* OS            : Linux(x86) (Linux Mint 13 Maya)(Linux Kernel 3.x.x)      */
  14.     /* Programmer    : Rahul.S                                                  */
  15.     /* Date          : 21-December-2014                                         */
  16.     /*=======================================================================*/
  17.  
  18.     /*=======================================================================*/
  19.     /* www.xanthium.in                                            */
  20.     /* Copyright (C) 2014 Rahul.S                                               */
  21.     /*=======================================================================*/
  22.     /*=======================================================================*/
  23.     /* Running the executable                                                   */
  24.         /* ----------------------------------------------------------------------*/
  25.     /* 1) Compile the  serialport_read.c  file using gcc on the terminal
  26.                 (without quotes)
  27.     */
  28.         /*                                                                    */
  29.     /*  " gcc -o serialport_read serialport_read.c "                            */
  30.     /*                                                                          */
  31.         /* 2) Linux will not allow you to access the serial port
  32.                             from user space,you have to be root.So use
  33.                 */
  34.         /*    "sudo" command to execute the compiled binary as super user.    */
  35.         /*                                                                    */
  36.         /*       "sudo ./serialport_read"                                     */
  37.     /*                                                                          */
  38.     /*=======================================================================*/
  39.  
  40.     /*=======================================================================*/
  41.     /* Sellecting the Serial port Number on Linux                               */
  42.     /* ----------------------------------------------------------------------*/
  43.     /* /dev/ttyUSBx - when using USB to Serial Converter,
  44.             where x can be 0,1,2...etc
  45.     */
  46.     /* /dev/ttySx   - for PC hardware based Serial ports,
  47.             where x can be 0,1,2...etc
  48.     */
  49.   /*=======================================================================*/
  50.  
  51.     /*-------------------------------------------------------------*/
  52.         /* termios structure -  /usr/include/asm-generic/termbits.h    */
  53.     /* use "man termios" to get more info about  termios structure */
  54.     /*-------------------------------------------------------------*/
  55.  
  56.         #include <stdio.h>
  57.         #include <fcntl.h>   /* File Control Definitions           */
  58.         #include <termios.h> /* POSIX Terminal Control Definitions */
  59.         #include <unistd.h>  /* UNIX Standard Definitions      */
  60.         #include <errno.h>   /* ERROR Number Definitions           */
  61.  
  62.             #include <time.h>
  63.  
  64.     void main(void)
  65.         {
  66.             int fd;/*File Descriptor*/
  67.  
  68.         printf("\n +----------------------------------+");
  69.         printf("\n |        Serial Port Read          |");
  70.         printf("\n +----------------------------------+");
  71.  
  72.         /*------------ Opening the Serial Port ------------*/
  73.  
  74.         /* Change /dev/ttyUSB0 to the one corresponding to your system */
  75.  
  76.             fd = open("/dev/ttyUSB0",O_RDWR | O_NOCTTY);
  77.                     /* ttyUSB0 is the FT232 based USB2SERIAL Converter   */
  78.                 /* O_RDWR   - Read/Write access to serial port       */
  79.                     /* O_NOCTTY - No terminal will control the process   */
  80.                     /* Open in blocking mode,read will wait              */
  81.  
  82.  
  83.  
  84.             if(fd == -1)                        /* Error Checking */
  85.                    printf("\n  Error! in Opening ttyUSB0  ");
  86.             else
  87.                    printf("\n  ttyUSB0 Opened Successfully ");
  88.  
  89.  
  90.         /*---------- Setting the Attributes of the serial port using termios structure --------- */
  91.  
  92.         struct termios SerialPortSettings;  /* Create the structure                          */
  93.  
  94.         tcgetattr(fd, &SerialPortSettings); /* Get the current attributes of the Serial port */
  95.  
  96.         /* Setting the Baud rate */
  97.         cfsetispeed(&SerialPortSettings,B9600); /* Set Read  Speed as 9600                       */
  98.         cfsetospeed(&SerialPortSettings,B9600); /* Set Write Speed as 9600                       */
  99.  
  100.         /* 8N1 Mode */
  101.         SerialPortSettings.c_cflag &= ~PARENB;      /* Disables the Parity Enable bit(PARENB),So No Parity   */
  102.         SerialPortSettings.c_cflag &= ~CSTOPB;      /* CSTOPB = 2 Stop bits,here it is cleared so 1 Stop bit */
  103.         SerialPortSettings.c_cflag &= ~CSIZE;           /* Clears the mask for setting the data size             */
  104.         SerialPortSettings.c_cflag |=  CS8;         /* Set the data bits = 8                                 */
  105.  
  106.         SerialPortSettings.c_cflag &= ~CRTSCTS;       /* No Hardware flow Control                         */
  107.         SerialPortSettings.c_cflag |= CREAD | CLOCAL; /* Enable receiver,Ignore Modem Control lines       */
  108.  
  109.  
  110.         SerialPortSettings.c_iflag &= ~(IXON | IXOFF | IXANY);          /* Disable XON/XOFF flow control both i/p and o/p */
  111.         SerialPortSettings.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG);  /* Non Cannonical mode                            */
  112.  
  113.         SerialPortSettings.c_oflag &= ~OPOST;/*No Output Processing*/
  114.  
  115.         /* Setting Time outs */
  116.         SerialPortSettings.c_cc[VMIN] = 10; /* Read at least 10 characters */
  117.         SerialPortSettings.c_cc[VTIME] = 0; /* Wait indefinetly   */
  118.         /* http://www.unixwiz.net/techtips/termios-vmin-vtime.html
  119.          * Helped me to figure out some things...
  120.          */
  121.  
  122.  
  123.         if((tcsetattr(fd,TCSANOW,&SerialPortSettings)) != 0) /* Set the attributes to the termios structure*/
  124.             printf("\n  ERROR ! in Setting attributes");
  125.         else
  126.             printf("\n  BaudRate = 9600 \n  StopBits = 1 \n  Parity   = none");
  127.  
  128.             /*------------------------------- Read data from serial port -----------------------------*/
  129.  
  130.         // tcflush(fd, TCIFLUSH);   /* Discards old data in the rx buffer            */
  131.     //
  132.         // char read_buffer[10];   /* Buffer to store the data received              */
  133.         // int  bytes_read = 0;    /* Number of bytes read by the read() system call */
  134.         // int i = 0;
  135.     //
  136.         // clock_t start = clock();
  137.         // bytes_read = read(fd,&read_buffer,10); /* Read the data                   */
  138.         // clock_t stop = clock();
  139.     //
  140.         // double elapsed = (double)(stop - start) * 1000.0 / CLOCKS_PER_SEC;
  141.         // printf("\n  Time elapsed in ms: %f", elapsed);
  142.     //
  143.         // printf("\n\n  Bytes Rxed -%d", bytes_read); /* Print the number of bytes read */
  144.         // printf("\n\n  ");
  145.     //
  146.         // start = clock();
  147.         // for(i=0;i<bytes_read;i++)     /*printing only the received characters*/
  148.         //     printf("%c",read_buffer[i]);
  149.         // stop = clock();
  150.     //
  151.         // elapsed = (double)(stop - start) * 1000.0 / CLOCKS_PER_SEC;
  152.         // printf("\n  Time elapsed in ms: %f", elapsed);
  153.     //
  154.     //
  155.         // printf("\n +----------------------------------+\n\n\n");
  156.  
  157.  
  158.         /* PLEASE NOTE:
  159.          * If you try transfer only 10 characters, it seems like its very slow
  160.          * but once you set it to receive them continiously they arrive at they
  161.          * expected rate. So, only first transfer takes longer...
  162.          */
  163.  
  164.         char read_buffer[10];   /* Buffer to store the data received              */
  165.         int  bytes_read = 0;    /* Number of bytes read by the read() system call */
  166.         int i = 0;
  167.  
  168.         while(1) {
  169.             tcflush(fd, TCIFLUSH);   /* Discards old data in the rx buffer            */
  170.             bytes_read = read(fd,&read_buffer,10); /* Read the data                   */
  171.  
  172.           printf("\n ");
  173.  
  174.             for(i=0;i<bytes_read;i++)    /*printing only the received characters*/
  175.                 printf("%c",read_buffer[i]);
  176.             printf("\n +----------------------------------+\n\n\n");
  177.         }
  178.  
  179.         close(fd); /* Close the serial port */
  180.  
  181. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement