Приложение последовательного порта Linux не работает - PullRequest
1 голос
/ 16 ноября 2011

Я пытаюсь подключить термопринтер с интерфейсом RS232.

Принтер работает нормально при использовании шпаклевки, терратерма и миникома.

Но я не могу заставить его работать с помощью программы на Си в Linux.

Следующая программа:

#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;

}

1 Ответ

1 голос
/ 28 марта 2012

Возможно, последовательный порт уже открыт другим приложением.

Используйте следующую строку, чтобы получить код ошибки и найти проблему.В open() вызове, tcsetattr() и write() ...

#include <error.h>

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