Monday 28 November 2011

Serial communication

Serial communication

Hello! I'm not sure if this goes here because is my first thread. I have a problem with some program that tries to send and receive info through serial port (virtual). I need to send 2 commands and I can do it properly but then I need to read info buf the program gets blocked...

The code is here
Code:

#include <stdio.h> // standard input / output functions
#include <string.h> // string function definitions
#include <unistd.h> // UNIX standard function definitions
#include <fcntl.h> // File control definitions
#include <errno.h> // Error number definitions
#include <termios.h> // POSIX terminal control definitionss
#include <time.h>  // time calls

int open_port(void)
{
        int fd; // file description for the serial port
        fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
        return(fd);
}

int configure_port(int fd)      // configure the port
{
        struct termios port_settings;      // structure to store the port settings in

        cfsetispeed(&port_settings, B19200);    // set baud rates
        cfsetospeed(&port_settings, B19200);

        port_settings.c_cflag &= ~PARENB;    // set no parity
        port_settings.c_cflag &= CSTOPB;    // 2 stop bytes
        port_settings.c_cflag &= CREAD;
        port_settings.c_cflag &= CLOCAL;
        port_settings.c_cflag &= ~CSIZE;    //8 bites of data
        port_settings.c_cflag |= CS8;     

        tcsetattr(fd, TCSANOW, &port_settings);    // apply the settings to the port NOW
        return(fd);

}

int read_info(int fd)  // query modem with an AT command
{
        char datos[10];
        char command = 0x53, address=0x52,size=0x07;
        sprintf(datos,"%c%c%c", command,address,0x57);
        write(fd,datos,3);
        sleep(1);
        printf("Frist write issued");
        command = 0x54, address=0x53;
        sprintf(datos,"%c%c%c", command,address,size);
        write(fd,datos,3);
        printf("Second write issued");
        int rd = read(fd,datos,7);//Here is the trouble!
        int i;
        for(i=0;i<10;i++) {printf("Datos[%d]: %c\n",i,datos[i]);}

}
int main(void)
{
        int fd = open_port();
        configure_port(fd);
        printf("PORT PREPARED!\n");
        read_info(fd);
        return(0);
}

I hope somebody can tell me what I'm doing wrong... and I have to say that the writing was okey so the parameters seem to be right too.

No comments:

Post a Comment