简体   繁体   中英

Linux serial port application not working

I m trying to interface a thermal printer which has an RS232 interface.

The printer works fine when used with putty, terraterm and minicom.

But I'm not able to make it work using C program in linux.

Following is the program :

#include <stdbool.h>
#include <time.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/poll.h>
#include <unistd.h>

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


#define _POSIX_SOURCE 1 /* POSIX compliant source */


struct termios options;


int main(void /*int argc,char *argv[]*/)
{
    int fd; /* File descriptor for the port */


      fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
      if (fd == -1)
      {
       /*
    * Could not open the port.
    */

    perror("open_port: Unable to open /dev/ttyS0 - ");
      }
      else
      {

    printf("Success\n");

        /*
     * Get the current options for the port...
     */

    tcgetattr(fd, &options);

        /*
         * Set the baud rates to 9600...
         */

    cfsetispeed(&options, B9600);
    cfsetospeed(&options, B9600);

    /*
     * Enable the receiver and set local mode...
     */

    options.c_cflag |= (CLOCAL | CREAD);



    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;

    options.c_cflag &= ~CRTSCTS;


    options.c_iflag |= (IXON | IXOFF | IXANY);

    /*
     * Set the new options for the port...
     */

    tcsetattr(fd, TCSANOW, &options);

    write(fd, "abcd", 4);

      }


      return 0;

}

There could be a possibility, that the serial port is already open by another application.

Use the following line to get the error code and find the problem. In open() call , tcsetattr() and write() ...

#include <error.h>

printf ("Error no is : %d\n", errno);
printf("Error description is : %s\n",strerror(errno));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM