GNU/Linux >> Tutoriales Linux >  >> Linux

Lectura y escritura en puerto serie en C en Linux

Resolví mis problemas, así que publico aquí el código correcto en caso de que alguien necesite algo similar.

Puerto abierto

int USB = open( "/dev/ttyUSB0", O_RDWR| O_NOCTTY );

Establecer parámetros

struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);

/* Error Handling */
if ( tcgetattr ( USB, &tty ) != 0 ) {
   std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
}

/* Save old tty parameters */
tty_old = tty;

/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);

/* Setting other Port Stuff */
tty.c_cflag     &=  ~PARENB;            // Make 8n1
tty.c_cflag     &=  ~CSTOPB;
tty.c_cflag     &=  ~CSIZE;
tty.c_cflag     |=  CS8;

tty.c_cflag     &=  ~CRTSCTS;           // no flow control
tty.c_cc[VMIN]   =  1;                  // read doesn't block
tty.c_cc[VTIME]  =  5;                  // 0.5 seconds read timeout
tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines

/* Make raw */
cfmakeraw(&tty);

/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) {
   std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}

Escribir

unsigned char cmd[] = "INIT \r";
int n_written = 0,
    spot = 0;

do {
    n_written = write( USB, &cmd[spot], 1 );
    spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);

Definitivamente no era necesario escribir byte por byte, también int n_written = write( USB, cmd, sizeof(cmd) -1) funcionó bien.

Por fin, leer :

int n = 0,
    spot = 0;
char buf = '\0';

/* Whole response*/
char response[1024];
memset(response, '\0', sizeof response);

do {
    n = read( USB, &buf, 1 );
    sprintf( &response[spot], "%c", buf );
    spot += n;
} while( buf != '\r' && n > 0);

if (n < 0) {
    std::cout << "Error reading: " << strerror(errno) << std::endl;
}
else if (n == 0) {
    std::cout << "Read nothing!" << std::endl;
}
else {
    std::cout << "Response: " << response << std::endl;
}

Este funcionó para mí. ¡Gracias a todos!


Linux
  1. Linux:¿el número principal de Tty de su Unix?

  2. Linux – ¿Puerto serie Raspberrypi?

  3. ¿Cómo conectar y enviar datos a un puerto serie Bluetooth en Linux?

  4. Linux – ¿Diferencia entre Pts y Tty?

  5. ¿Puerta de enlace de puerto serie Netbsd?

Cómo controlar puertos periféricos:Acceso y escritura en puerto paralelo con C en Linux. Parte I

Cómo encontrar y cerrar puertos abiertos en Linux

Linux:¿cómo cambiar entre la sesión Tty y Xorg?

Abrir un puerto en Linux

Cómo y por qué usar Linux para instalar Telnet

dd se vuelve más lento al leer y escribir