By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,286 Members | 2,422 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,286 IT Pros & Developers. It's quick & easy.

reading data from barcode scanner using c++

P: 20
hi,
Can anyone tell me,how to read data from a barcode reader using C++ on linux?. I have connected my barcode scanner in com1(dev/ttys0) and I am using minicom for communication.If any1 has any info pliz mail me.

Tanks in Advance.
Nov 28 '06 #1
Share this Question
Share on Google+
5 Replies


Expert 100+
P: 1,510
hi,
Can anyone tell me,how to read data from a barcode reader using C++ on linux?. I have connected my barcode scanner in com1(dev/ttys0) and I am using minicom for communication.If any1 has any info pliz mail me.

Tanks in Advance.
if you know the format of the data from the barcode reader you can write a C/C++ program to read characters from the serial port and decode the information. Have a look at
http://www.comptechdoc.org/os/linux/...pgcserial.html

also the following program works with DEV-C++ and cygwin (using gcc and mingw) under windows so to use it under Linux you would need to change the com1 specification to dev/ttys0
Expand|Select|Wrap|Line Numbers
  1. // terminal.c - simple terminal program for Dev-C++ and Cygwin
  2. //
  3. // only works for one port at moment
  4. //
  5. #include <conio.h>
  6. #include <stdio.h>
  7. #include <windows.h>
  8.  
  9.  
  10. HANDLE hCom;           //handle for serial port I/O
  11.  
  12. /*----------------------------------------------------------------------------*
  13.  * Serial port: initialise io_port, set baud rate, set data bits, one stop bit*/
  14.  
  15. HANDLE rs_initialise (int io_port, const long int BaudRate, const char parity, const char data)
  16. {
  17.     BOOL bPortReady;
  18.     DCB dcb;
  19.     char ComPortName[]="COM1";           // set up COM port number in COM?
  20.     ComPortName[3]='0'+io_port;
  21.     hCom = CreateFile(ComPortName, GENERIC_READ | GENERIC_WRITE,
  22.                                   0,            // exclusive access
  23.                                   NULL,         // no security
  24.                                   OPEN_EXISTING,
  25.                                   0,            // no overlapped I/O
  26.                                   NULL);        // null template
  27.  
  28.  
  29.     if ((int)hCom <= 0) { printf("serial port COM%d connect fail %s error %d\n\r", io_port, ComPortName, GetLastError()); return 0;   } 
  30.     //else                printf(" serial port COM%d connect OK \n\r", io_port); 
  31.  
  32.     bPortReady = SetupComm(hCom, 2, 128); // set buffer sizes
  33.     if (!bPortReady ) { printf("serial port COM%d SetupComm fail  %d\n\r", io_port,  GetLastError()); return 0;   } 
  34.     //else                printf(" serial port COM%d connect OK \n\r", io_port); 
  35.  
  36.     bPortReady = GetCommState(hCom, &dcb);
  37.     if (!bPortReady ) { printf("serial port COM%d  GetCommState fail  %d\n\r", io_port,  GetLastError()); return 0;   } 
  38.   //  else                printf(" serial port COM%d connect OK \n\r", io_port); 
  39.     dcb.BaudRate = BaudRate;
  40.     if( data == '7') dcb.ByteSize = 7;
  41.     else             dcb.ByteSize = 8;
  42.     if( parity == 'E') dcb.Parity = EVENPARITY;
  43.     if( parity == 'O') dcb.Parity = ODDPARITY;
  44.     else               dcb.Parity = NOPARITY;
  45.     dcb.StopBits = ONESTOPBIT;
  46.     dcb.fAbortOnError = TRUE;
  47.  
  48.     // set XON/XOFF
  49.     dcb.fOutX = FALSE;                       // XON/XOFF off for transmit
  50.     dcb.fInX = FALSE;                        // XON/XOFF off for receive
  51.     // set RTSCTS
  52.     dcb.fOutxCtsFlow = FALSE;               // turn off CTS flow control
  53.     dcb.fRtsControl = FALSE;                // RTS_CONTROL_HANDSHAKE; //
  54.     // set DSRDTR
  55.     dcb.fOutxDsrFlow = FALSE;               // turn off DSR flow control
  56.     //dcb.fDtrControl = DTR_CONTROL_ENABLE; // DTR handshake
  57.     dcb.fDtrControl = DTR_CONTROL_DISABLE;  //
  58.     // dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; //
  59.  
  60.     bPortReady = SetCommState(hCom, &dcb);
  61.     if (!bPortReady ) { printf("serial port COM%d  SetCommState fail  %d\n\r", io_port,  GetLastError()); return 0;   } 
  62.  
  63.     // Communication timeouts 
  64.     COMMTIMEOUTS CommTimeouts;
  65.     bPortReady = GetCommTimeouts (hCom, &CommTimeouts);
  66.     CommTimeouts.ReadIntervalTimeout = 5 ;
  67.     CommTimeouts.ReadTotalTimeoutConstant = 5 ;
  68.     CommTimeouts.ReadTotalTimeoutMultiplier = 1 ;
  69.     CommTimeouts.WriteTotalTimeoutConstant = 5 ;
  70.     CommTimeouts.WriteTotalTimeoutMultiplier = 1 ;
  71.     bPortReady = SetCommTimeouts (hCom, &CommTimeouts);
  72.     if (!bPortReady ) { printf("serial port COM%d SetCommTimeouts fail  %d\n\r", io_port,  GetLastError()); return 0;   } 
  73.     else                printf(" serial port COM%d connect OK \n\r", io_port); 
  74.     return hCom;
  75. }
  76.  
  77.  
  78. /*----------------------------------------------------------------------------*
  79.  * Serial port: terminate io_port, sets DTR and RTS to low                     */
  80. void rs_terminate(const int io_port)
  81. {
  82.   // Close(hCom);
  83. }
  84.  
  85.  
  86.  
  87. /*----------------------------------------------------------------------------*
  88.  * Serial port: read character from io_port (ignored in this version)         */
  89. char rs_getch(const int io_port)
  90. {
  91.     char rxchar;
  92.     BOOL bReadRC;
  93.     static DWORD iBytesRead;
  94.     bReadRC = ReadFile(hCom, &rxchar, 1, &iBytesRead, NULL);
  95.     if (iBytesRead) return rxchar; else return 0;         // return 0 if no character read
  96. }
  97.  
  98. /*----------------------------------------------------------------------------*
  99.  * Serial port: transmit character to io_port                                 */
  100. void rs_putch(const int io_port, const int txchar)
  101. {
  102.     BOOL bWriteRC;
  103.     static DWORD iBytesWritten;
  104.     bWriteRC = WriteFile(hCom, &txchar, 1, &iBytesWritten,NULL);
  105.     return;
  106. }
  107.  
  108. /*----------------------------------------------------------------------------*
  109.  * Serial port: transmit a string of characters to io_port                    */
  110. void rs_putstring(const int io_port, const char *string)
  111. {
  112.     while (*string != '\0')
  113.         rs_putch(io_port, *string++);
  114. }
  115.  
  116. //#include <conio.h>
  117.  
  118. int main()
  119. {
  120.     int port = 1;
  121.     if(!rs_initialise(port ,57600, '8', 'N')) { getch(); exit(1); }
  122.     char letter;
  123.     while(1)
  124.      {
  125.       if (kbhit())  rs_putch(port, getche());             // if keyboard hit read character and transmit it  
  126.       if((letter=rs_getch(port))>0) 
  127.          { putchar(letter); if(letter=='\r')   putchar('\n'); }     // if character received display it
  128.      }
  129.     getch();
  130.     return 0;
  131. }
  132.  
  133.  
Nov 28 '06 #2

P: 20
if you know the format of the data from the barcode reader you can write a C/C++ program to read characters from the serial port and decode the information. Have a look at
http://www.comptechdoc.org/os/linux/...pgcserial.html

also the following program works with DEV-C++ and cygwin (using gcc and mingw) under windows so to use it under Linux you would need to change the com1 specification to dev/ttys0
Expand|Select|Wrap|Line Numbers
  1. // terminal.c - simple terminal program for Dev-C++ and Cygwin
  2. //
  3. // only works for one port at moment
  4. //
  5. #include <conio.h>
  6. #include <stdio.h>
  7. #include <windows.h>
  8.  
  9.  
  10. HANDLE hCom;           //handle for serial port I/O
  11.  
  12. /*----------------------------------------------------------------------------*
  13.  * Serial port: initialise io_port, set baud rate, set data bits, one stop bit*/
  14.  
  15. HANDLE rs_initialise (int io_port, const long int BaudRate, const char parity, const char data)
  16. {
  17.     BOOL bPortReady;
  18.     DCB dcb;
  19.     char ComPortName[]="COM1";           // set up COM port number in COM?
  20.     ComPortName[3]='0'+io_port;
  21.     hCom = CreateFile(ComPortName, GENERIC_READ | GENERIC_WRITE,
  22.                                   0,            // exclusive access
  23.                                   NULL,         // no security
  24.                                   OPEN_EXISTING,
  25.                                   0,            // no overlapped I/O
  26.                                   NULL);        // null template
  27.  
  28.  
  29.     if ((int)hCom <= 0) { printf("serial port COM%d connect fail %s error %d\n\r", io_port, ComPortName, GetLastError()); return 0;   } 
  30.     //else                printf(" serial port COM%d connect OK \n\r", io_port); 
  31.  
  32.     bPortReady = SetupComm(hCom, 2, 128); // set buffer sizes
  33.     if (!bPortReady ) { printf("serial port COM%d SetupComm fail  %d\n\r", io_port,  GetLastError()); return 0;   } 
  34.     //else                printf(" serial port COM%d connect OK \n\r", io_port); 
  35.  
  36.     bPortReady = GetCommState(hCom, &dcb);
  37.     if (!bPortReady ) { printf("serial port COM%d  GetCommState fail  %d\n\r", io_port,  GetLastError()); return 0;   } 
  38.   //  else                printf(" serial port COM%d connect OK \n\r", io_port); 
  39.     dcb.BaudRate = BaudRate;
  40.     if( data == '7') dcb.ByteSize = 7;
  41.     else             dcb.ByteSize = 8;
  42.     if( parity == 'E') dcb.Parity = EVENPARITY;
  43.     if( parity == 'O') dcb.Parity = ODDPARITY;
  44.     else               dcb.Parity = NOPARITY;
  45.     dcb.StopBits = ONESTOPBIT;
  46.     dcb.fAbortOnError = TRUE;
  47.  
  48.     // set XON/XOFF
  49.     dcb.fOutX = FALSE;                       // XON/XOFF off for transmit
  50.     dcb.fInX = FALSE;                        // XON/XOFF off for receive
  51.     // set RTSCTS
  52.     dcb.fOutxCtsFlow = FALSE;               // turn off CTS flow control
  53.     dcb.fRtsControl = FALSE;                // RTS_CONTROL_HANDSHAKE; //
  54.     // set DSRDTR
  55.     dcb.fOutxDsrFlow = FALSE;               // turn off DSR flow control
  56.     //dcb.fDtrControl = DTR_CONTROL_ENABLE; // DTR handshake
  57.     dcb.fDtrControl = DTR_CONTROL_DISABLE;  //
  58.     // dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; //
  59.  
  60.     bPortReady = SetCommState(hCom, &dcb);
  61.     if (!bPortReady ) { printf("serial port COM%d  SetCommState fail  %d\n\r", io_port,  GetLastError()); return 0;   } 
  62.  
  63.     // Communication timeouts 
  64.     COMMTIMEOUTS CommTimeouts;
  65.     bPortReady = GetCommTimeouts (hCom, &CommTimeouts);
  66.     CommTimeouts.ReadIntervalTimeout = 5 ;
  67.     CommTimeouts.ReadTotalTimeoutConstant = 5 ;
  68.     CommTimeouts.ReadTotalTimeoutMultiplier = 1 ;
  69.     CommTimeouts.WriteTotalTimeoutConstant = 5 ;
  70.     CommTimeouts.WriteTotalTimeoutMultiplier = 1 ;
  71.     bPortReady = SetCommTimeouts (hCom, &CommTimeouts);
  72.     if (!bPortReady ) { printf("serial port COM%d SetCommTimeouts fail  %d\n\r", io_port,  GetLastError()); return 0;   } 
  73.     else                printf(" serial port COM%d connect OK \n\r", io_port); 
  74.     return hCom;
  75. }
  76.  
  77.  
  78. /*----------------------------------------------------------------------------*
  79.  * Serial port: terminate io_port, sets DTR and RTS to low                     */
  80. void rs_terminate(const int io_port)
  81. {
  82.   // Close(hCom);
  83. }
  84.  
  85.  
  86.  
  87. /*----------------------------------------------------------------------------*
  88.  * Serial port: read character from io_port (ignored in this version)         */
  89. char rs_getch(const int io_port)
  90. {
  91.     char rxchar;
  92.     BOOL bReadRC;
  93.     static DWORD iBytesRead;
  94.     bReadRC = ReadFile(hCom, &rxchar, 1, &iBytesRead, NULL);
  95.     if (iBytesRead) return rxchar; else return 0;         // return 0 if no character read
  96. }
  97.  
  98. /*----------------------------------------------------------------------------*
  99.  * Serial port: transmit character to io_port                                 */
  100. void rs_putch(const int io_port, const int txchar)
  101. {
  102.     BOOL bWriteRC;
  103.     static DWORD iBytesWritten;
  104.     bWriteRC = WriteFile(hCom, &txchar, 1, &iBytesWritten,NULL);
  105.     return;
  106. }
  107.  
  108. /*----------------------------------------------------------------------------*
  109.  * Serial port: transmit a string of characters to io_port                    */
  110. void rs_putstring(const int io_port, const char *string)
  111. {
  112.     while (*string != '\0')
  113.         rs_putch(io_port, *string++);
  114. }
  115.  
  116. //#include <conio.h>
  117.  
  118. int main()
  119. {
  120.     int port = 1;
  121.     if(!rs_initialise(port ,57600, '8', 'N')) { getch(); exit(1); }
  122.     char letter;
  123.     while(1)
  124.      {
  125.       if (kbhit())  rs_putch(port, getche());             // if keyboard hit read character and transmit it  
  126.       if((letter=rs_getch(port))>0) 
  127.          { putchar(letter); if(letter=='\r')   putchar('\n'); }     // if character received display it
  128.      }
  129.     getch();
  130.     return 0;
  131. }
  132.  
  133.  



Hi, thank you very much for your reply.I have posted this question in some other discussion forum also.But nobody answered me.you are the only person who answered this question.

I tried to compile the program,which you have sent.But it is giving the following errors:(I am using gcc 4.0 and my OS is ubuntu(Linux)).

terminal.c:5:19: error: conio.h: No such file or directory
terminal.c:7:21: error: windows.h: No such file or directory
terminal.c:10: error: ‘HANDLE’ does not name a type
terminal.c:15: error: ‘HANDLE’ does not name a type
terminal.c: In function ‘char rs_getch(int)’:
terminal.c:92: error: ‘BOOL’ was not declared in this scope
terminal.c:92: error: expected `;' before ‘bReadRC’
terminal.c:93: error: ‘DWORD’ does not name a type
terminal.c:94: error: ‘bReadRC’ was not declared in this scope
terminal.c:94: error: ‘hCom’ was not declared in this scope
terminal.c:94: error: ‘iBytesRead’ was not declared in this scope
terminal.c:94: error: ‘ReadFile’ was not declared in this scope
terminal.c: In function ‘void rs_putch(int, int)’:
terminal.c:102: error: ‘BOOL’ was not declared in this scope
terminal.c:102: error: expected `;' before ‘bWriteRC’
terminal.c:103: error: ‘DWORD’ does not name a type
terminal.c:104: error: ‘bWriteRC’ was not declared in this scope
terminal.c:104: error: ‘hCom’ was not declared in this scope
terminal.c:104: error: ‘iBytesWritten’ was not declared in this scope
terminal.c:104: error: ‘WriteFile’ was not declared in this scope
terminal.c: In function ‘int main()’:
terminal.c:121: error: ‘rs_initialise’ was not declared in this scope
terminal.c:121: error: ‘getch’ was not declared in this scope
terminal.c:121: error: ‘exit’ was not declared in this scope
terminal.c:125: error: ‘kbhit’ was not declared in this scope
terminal.c:125: error: ‘getche’ was not declared in this scope
terminal.c:129: error: ‘getch’ was not declared in this scope

I HOPE YOU WILL GIVE A BETTER SOLUTION.

THANKS
Nov 29 '06 #3

Expert 100+
P: 1,510
I posted the Cygwin version which uses <windows.h>

the version bwlow was adapted from
http://www.comptechdoc.org/os/linux/programming/c/linux_pgcserial.html

and works under SUSE Linux enterprise 10.1

Expand|Select|Wrap|Line Numbers
  1. // terminal.c - simple terminal program for Linux
  2. // adapted from
  3. //    http://www.comptechdoc.org/os/linux/programming/c/linux_pgcserial.html
  4. // also see
  5. //   http://www.lafn.org/~dave/linux/Serial-Programming-HOWTO.txt
  6. //
  7. // only works for one port at moment
  8. //
  9. #include <termios.h>
  10. #include <stdio.h>
  11. #include <unistd.h>
  12. #include <fcntl.h>
  13. #include <sys/signal.h>
  14. #include <sys/types.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17.  
  18. #define FALSE 0
  19. #define TRUE 1
  20. #define BAUDRATE B38400
  21. volatile int STOP=FALSE;
  22.  
  23. void signal_handler_IO (int status);    //definition of signal handler
  24. int wait_flag=TRUE;                     //TRUE while no signal received
  25. long Baud_Rate = 38400;         // default Baud Rate (110 through 38400)
  26. long BAUD;                      // derived baud rate from command line
  27. long DATABITS;
  28. long STOPBITS;
  29. long PARITYON;
  30. long PARITY;
  31. int Data_Bits = 8;              // Number of data bits
  32. int Stop_Bits = 1;              // Number of stop bits
  33. int Parity = 0;                 // Parity as follows:
  34.                   // 00 = NONE, 01 = Odd, 02 = Even, 03 = Mark, 04 = Space
  35.  
  36.  
  37.    int fd, tty, error;
  38.    struct termios oldtio, newtio;       //place for old and new port settings for serial port
  39.    struct termios oldkey, newkey;       //place tor old and new port settings for keyboard teletype
  40.    struct sigaction saio;               //definition of signal action
  41.  
  42. /*----------------------------------------------------------------------------*
  43.  * Serial port: initialise io_port, set baud rate, set data bits, one stop bit*/
  44.  
  45. int rs_initialise (int io_port, const long int BaudRate, const char parity, const char data)
  46. {
  47.       // set new port settings for non-canonical input processing  //must be NOCTTY
  48.       newkey.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
  49.       newkey.c_iflag = IGNPAR;
  50.       newkey.c_oflag = 0;
  51.       newkey.c_lflag = 0;       //ICANON;
  52.       newkey.c_cc[VMIN]=1;
  53.       newkey.c_cc[VTIME]=0;
  54.       tcflush(tty, TCIFLUSH);
  55.       tcsetattr(tty,TCSANOW,&newkey);
  56.  
  57.       switch (BaudRate)
  58.       {
  59.          case 38400:
  60.          default:
  61.             BAUD = B38400;
  62.             break;
  63.          case 19200:
  64.             BAUD  = B19200;
  65.             break;
  66.          case 9600:
  67.             BAUD  = B9600;
  68.             break;
  69.          case 4800:
  70.             BAUD  = B4800;
  71.             break;
  72.          case 2400:
  73.             BAUD  = B2400;
  74.             break;
  75.          case 1800:
  76.             BAUD  = B1800;
  77.             break;
  78.          case 1200:
  79.             BAUD  = B1200;
  80.             break;
  81.          case 600:
  82.             BAUD  = B600;
  83.             break;
  84.          case 300:
  85.             BAUD  = B300;
  86.             break;
  87.          case 200:
  88.             BAUD  = B200;
  89.             break;
  90.          case 150:
  91.             BAUD  = B150;
  92.             break;
  93.          case 134:
  94.             BAUD  = B134;
  95.             break;
  96.          case 110:
  97.             BAUD  = B110;
  98.             break;
  99.          case 75:
  100.             BAUD  = B75;
  101.             break;
  102.          case 50:
  103.             BAUD  = B50;
  104.             break;
  105.       }  //end of switch baud_rate
  106.       switch (Data_Bits)
  107.       {
  108.          case 8:
  109.          default:
  110.             DATABITS = CS8;
  111.             break;
  112.          case 7:
  113.             DATABITS = CS7;
  114.             break;
  115.          case 6:
  116.             DATABITS = CS6;
  117.             break;
  118.          case 5:
  119.             DATABITS = CS5;
  120.             break;
  121.       }  //end of switch data_bits
  122.       switch (Stop_Bits)
  123.       {
  124.          case 1:
  125.          default:
  126.             STOPBITS = 0;
  127.             break;
  128.          case 2:
  129.             STOPBITS = CSTOPB;
  130.             break;
  131.       }  //end of switch stop bits
  132.       switch (Parity)
  133.       {
  134.          case 0:
  135.          default:                       //none
  136.             PARITYON = 0;
  137.             PARITY = 0;
  138.             break;
  139.          case 1:                        //odd
  140.             PARITYON = PARENB;
  141.             PARITY = PARODD;
  142.             break;
  143.          case 2:                        //even
  144.             PARITYON = PARENB;
  145.             PARITY = 0;
  146.             break;
  147.       }  //end of switch parity
  148.  
  149.       //open the device(com port) to be non-blocking (read will return immediately)
  150.       fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NONBLOCK);
  151.       if (fd < 0)
  152.       {
  153.          perror("/dev/ttyS0");
  154.          return 0;
  155.       }
  156.  
  157.       //install the serial handler before making the device asynchronous
  158.       saio.sa_handler = signal_handler_IO;
  159.       sigemptyset(&saio.sa_mask);   //saio.sa_mask = 0;
  160.       saio.sa_flags = 0;
  161.       saio.sa_restorer = NULL;
  162.       sigaction(SIGIO,&saio,NULL);
  163.  
  164.       // allow the process to receive SIGIO
  165.       fcntl(fd, F_SETOWN, getpid());
  166.       // Make the file descriptor asynchronous (the manual page says only
  167.       // O_APPEND and O_NONBLOCK, will work with F_SETFL...)
  168.       fcntl(fd, F_SETFL, O_ASYNC);//FASYNC);
  169.  
  170.       tcgetattr(fd,&oldtio); // save current port settings 
  171.       // set new port settings for canonical input processing 
  172.       newtio.c_cflag = BAUD | CRTSCTS | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;
  173.       newtio.c_iflag = IGNPAR;
  174.       newtio.c_oflag = 0;
  175.       newtio.c_lflag = 0;       //ICANON;
  176.       newtio.c_cc[VMIN]=1;
  177.       newtio.c_cc[VTIME]=0;
  178.       tcflush(fd, TCIFLUSH);
  179.       tcsetattr(fd,TCSANOW,&newtio);
  180.       return 1;    // OK
  181. }
  182.  
  183.  
  184. /*----------------------------------------------------------------------------*
  185.  * Serial port: terminate io_port, sets DTR and RTS to low                     */
  186. void rs_terminate(const int io_port)
  187. {
  188.      // restore old port settings
  189.       tcsetattr(fd,TCSANOW,&oldtio);
  190.       tcsetattr(tty,TCSANOW,&oldkey);
  191.       close(fd);        //close the com port
  192. }
  193.  
  194.  
  195.  
  196. /*----------------------------------------------------------------------------*
  197.  * Serial port: read character from io_port (ignored in this version)         */
  198. char rs_getch(const int io_port)
  199. {
  200.    static char buf[255];                       // buffer for where data is put
  201.    static int index = 0, count = 0;
  202.    // check if data already in input buffer - if so return a character
  203.    if(count>0) { count--; return buf[index++]; }
  204.    // otherwise check if any characters receivedfrom serial line
  205.    if (wait_flag==FALSE)  //if input is available
  206.          {
  207.             count = read(fd,buf,255);
  208.             wait_flag = TRUE;      /* wait for new input */
  209.             index=0;
  210.             count--;
  211.             return buf[index++];   // return first character
  212.          }
  213.        return 0;         // return 0 if no character read
  214. }
  215.  
  216. /*----------------------------------------------------------------------------*
  217.  * Serial port: transmit character to io_port                                 */
  218. void rs_putch(const int io_port, const int txchar)
  219. {
  220.        write(fd,&txchar,1);          //write 1 byte to the port
  221.  }
  222.  
  223. /*----------------------------------------------------------------------------*
  224.  * Serial port: transmit a string of characters to io_port                    */
  225. void rs_putstring(const int io_port, const char *string)
  226. {
  227.     while (*string != '\0')
  228.         rs_putch(io_port, *string++);
  229. }
  230.  
  231. /***************************************************************************
  232. * signal handler. sets wait_flag to FALSE, to indicate above loop that     *
  233. * characters have been received.                                           *
  234. ***************************************************************************/
  235.  
  236. void signal_handler_IO (int status)
  237. {
  238.     //printf("received SIGIO signal.\n");
  239.    wait_flag = FALSE;
  240. }
  241.  
  242.  
  243.  
  244. // -------------------------------------------------------------------------------------//
  245.  
  246. FILE *input;
  247. FILE *output;
  248.  
  249. // open keyboard/screen terminal functions
  250. void terminal_open()
  251. {
  252.    input = fopen("/dev/tty", "r");      //open the terminal keyboard
  253.    output = fopen("/dev/tty", "w");     //open the terminal screen
  254.  
  255.    if (!input || !output)
  256.    {
  257.       fprintf(stderr, "Unable to open /dev/tty\n");
  258.       exit(1);
  259.    }
  260.    tty = open("/dev/tty", O_RDWR | O_NOCTTY | O_NONBLOCK); //set the user console port up
  261.    tcgetattr(tty,&oldkey); // save current port settings   //so commands are interpreted right for this program
  262.    fputs("Linux terminal program\n\n",output);               //display the program introduction
  263. }
  264.  
  265. // close keyboard/screen
  266. void terminal_close()
  267. {
  268.       close(tty);
  269. }
  270.  
  271. // output character to screen
  272. void terminal_putchar(int ch)
  273. {
  274.     fputc(ch,output);
  275.     fflush(output);
  276. }
  277.  
  278. // if keyboard was hit return character else 0
  279. int terminal_getchar()
  280. {
  281.     int status, Key;
  282.     status = fread(&Key,1,1,input);
  283.     if (status==1) return Key;       //if a key was hit
  284.     else           return 0;         // else return 0
  285. }
  286.  
  287. // main terminal program
  288. int main()
  289. {
  290.    int port = 1;
  291.    terminal_open();
  292.    error=0;
  293.     // open the RS232 serial line
  294.     if(!rs_initialise(port ,9600, '8', 'N')) {  exit(1); }
  295.     char letter;
  296.     while(!STOP)
  297.      {
  298.          // if keyboard hit read character and transmit it   
  299.         if((letter=terminal_getchar())>0)      // if character received display it
  300.          {
  301.             if(letter ==  0x1b) break;           // Esc to EXIT program
  302.             terminal_putchar(letter);         // remove for no echo
  303.             rs_putch(port, letter);
  304.           }  
  305.  
  306.         if((letter=rs_getch(port))>0)             // if character received display it
  307.          { 
  308.           terminal_putchar(letter);; 
  309.           if(letter=='\r') terminal_putchar('\n'); 
  310.          }    
  311.      }
  312.     rs_terminate(port);
  313.     terminal_close();
  314.     return 0;
  315. }
  316.  
Nov 29 '06 #4

P: 20
Hi, The program what you have sent is working fine. But there is a small issue, when I try to read the barcode at first time, it is giving the correct output. But at the second time, when I read some other barcode, it is giving the same output(what I got at the first time). If your time permits, plz help me to solve this problem.

#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>

#define FALSE 0
#define TRUE 1
#define BAUDRATE B38400
volatile int STOP=FALSE;

void signal_handler_IO (int status); //definition of signal handler
int wait_flag=TRUE; //TRUE while no signal received
long Baud_Rate = 38400; // default Baud Rate (110 through 38400)
long BAUD; // derived baud rate from command line
long DATABITS;
long STOPBITS;
long PARITYON;
long PARITY;
int Data_Bits = 8; // Number of data bits
int Stop_Bits = 1; // Number of stop bits
int Parity = 0; // Parity as follows:
// 00 = NONE, 01 = Odd, 02 = Even, 03 = Mark, 04 = Space


int fd, tty, error;
struct termios oldtio, newtio; //place for old and new port settings for serial port
struct termios oldkey, newkey; //place tor old and new port settings for keyboard teletype
struct sigaction saio; //definition of signal action

/*----------------------------------------------------------------------------*
* Serial port: initialise io_port, set baud rate, set data bits, one stop bit*/

int rs_initialise (int io_port, const long int BaudRate, const char parity, const char data)
{
// set new port settings for non-canonical input processing //must be NOCTTY
newkey.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
newkey.c_iflag = IGNPAR;
newkey.c_oflag = 0;
newkey.c_lflag = 0; //ICANON;
newkey.c_cc[VMIN]=1;
newkey.c_cc[VTIME]=0;
tcflush(tty, TCIFLUSH);
tcsetattr(tty,TCSANOW,&newkey);

switch (BaudRate)
{
case 38400:
default:
BAUD = B38400;
break;
case 19200:
BAUD = B19200;
break;
case 9600:
BAUD = B9600;
break;
case 4800:
BAUD = B4800;
break;
case 2400:
BAUD = B2400;
break;
case 1800:
BAUD = B1800;
break;
case 1200:
BAUD = B1200;
break;
case 600:
BAUD = B600;
break;
case 300:
BAUD = B300;
break;
case 200:
BAUD = B200;
break;
case 150:
BAUD = B150;
break;
case 134:
BAUD = B134;
break;
case 110:
BAUD = B110;
break;
case 75:
BAUD = B75;
break;
case 50:
BAUD = B50;
break;
} //end of switch baud_rate
switch (Data_Bits)
{
case 8:
default:
DATABITS = CS8;
break;
case 7:
DATABITS = CS7;
break;
case 6:
DATABITS = CS6;
break;
case 5:
DATABITS = CS5;
break;
} //end of switch data_bits
switch (Stop_Bits)
{
case 1:
default:
STOPBITS = 0;
break;
case 2:
STOPBITS = CSTOPB;
break;
} //end of switch stop bits
switch (Parity)
{
case 0:
default: //none
PARITYON = 0;
PARITY = 0;
break;
case 1: //odd
PARITYON = PARENB;
PARITY = PARODD;
break;
case 2: //even
PARITYON = PARENB;
PARITY = 0;
break;
} //end of switch parity

//open the device(com port) to be non-blocking (read will return immediately)
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd < 0)
{
perror("/dev/ttyS0");
return 0;
}

//install the serial handler before making the device asynchronous
saio.sa_handler = signal_handler_IO;
sigemptyset(&saio.sa_mask); //saio.sa_mask = 0;
saio.sa_flags = 0;
saio.sa_restorer = NULL;
sigaction(SIGIO,&saio,NULL);

// allow the process to receive SIGIO
fcntl(fd, F_SETOWN, getpid());
// Make the file descriptor asynchronous (the manual page says only
// O_APPEND and O_NONBLOCK, will work with F_SETFL...)
fcntl(fd, F_SETFL, O_ASYNC);//FASYNC);

tcgetattr(fd,&oldtio); // save current port settings
// set new port settings for canonical input processing
newtio.c_cflag = BAUD | CRTSCTS | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag = 0; //ICANON;
newtio.c_cc[VMIN]=1;
newtio.c_cc[VTIME]=0;
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
return 1; // OK
}


/*----------------------------------------------------------------------------*
* Serial port: terminate io_port, sets DTR and RTS to low */
void rs_terminate(const int io_port)
{
// restore old port settings
tcsetattr(fd,TCSANOW,&oldtio);
tcsetattr(tty,TCSANOW,&oldkey);
close(fd); //close the com port
}



/*----------------------------------------------------------------------------*
* Serial port: read character from io_port (ignored in this version) */
char rs_getch(const int io_port)
{
static char buf[255]; // buffer for where data is put
static int index = 0, count = 0;
// check if data already in input buffer - if so return a character
if(count>0) { count--; return buf[index++]; }
// otherwise check if any characters receivedfrom serial line
if (wait_flag==FALSE) //if input is available
{
count = read(fd,buf,255);
wait_flag = TRUE; /* wait for new input */
index=0;
count--;
return buf[index++]; // return first character
}
return 0; // return 0 if no character read
}

/*----------------------------------------------------------------------------*
* Serial port: transmit character to io_port */
void rs_putch(const int io_port, const int txchar)
{
write(fd,&txchar,1); //write 1 byte to the port
}

/*----------------------------------------------------------------------------*
* Serial port: transmit a string of characters to io_port */
void rs_putstring(const int io_port, const char *string)
{
while (*string != '\0')
rs_putch(io_port, *string++);
}

/************************************************** *************************
* signal handler. sets wait_flag to FALSE, to indicate above loop that *
* characters have been received. *
************************************************** *************************/

void signal_handler_IO (int status)
{
//printf("received SIGIO signal.\n");
wait_flag = FALSE;
}



// -------------------------------------------------------------------------------------//

FILE *input;
FILE *output;

// open keyboard/screen terminal functions
void terminal_open()
{
input = fopen("/dev/tty", "r"); //open the terminal keyboard
output = fopen("/dev/tty", "w"); //open the terminal screen

if (!input || !output)
{
fprintf(stderr, "Unable to open /dev/tty\n");
exit(1);
}
tty = open("/dev/tty", O_RDWR | O_NOCTTY | O_NONBLOCK); //set the user console port up
tcgetattr(tty,&oldkey); // save current port settings //so commands are interpreted right for this program
fputs("Linux terminal program\n\n",output); //display the program introduction
}

// close keyboard/screen
void terminal_close()
{
close(tty);
}

// output character to screen
void terminal_putchar(int ch)
{
fputc(ch,output);
fflush(output);
}

// if keyboard was hit return character else 0
int terminal_getchar()
{
int status, Key;
status = fread(&Key,1,1,input);
if (status==1) return Key; //if a key was hit
else return 0; // else return 0
}

// main terminal program
int main()
{
int port = 1;
terminal_open();
error=0;
// open the RS232 serial line
if(!rs_initialise(port ,9600, '8', 'N')) { exit(1); }
char letter;
while(!STOP)
{
// if keyboard hit read character and transmit it
if((letter=terminal_getchar())>0) // if character received display it
{
if(letter == 0x1b) break; // Esc to EXIT program
terminal_putchar(letter); // remove for no echo
rs_putch(port, letter);
}

if((letter=rs_getch(port))>0) // if character received display it
{
terminal_putchar(letter);;
if(letter=='\r') terminal_putchar('\n');
}
}
rs_terminate(port);
terminal_close();
return 0;
}
Feb 2 '07 #5

Post your reply

Sign in to post your reply or Sign up for a free account.