2
#include <stdio.h>
    #include <fcntl.h>       /* File Control Definitions           */
    #include <termios.h>     /* POSIX Terminal Control Definitions */
    #include <unistd.h>      /* UNIX Standard Definitions          */ 
    #include <errno.h>       /* ERROR Number Definitions           */
#include <sys/ioctl.h>   /* ioctl()                            */

    void main(void)
    {
        int fd;/*File Descriptor*/

    printf("\n +----------------------------------+");
    printf("\n |        USB To RS485 Write        |");
    printf("\n +----------------------------------+");

    /*------------------------------- Opening the Serial Port -------------------------------*/

    /* Change /dev/ttyUSB0 to the one corresponding to your system */

        fd = open("/dev/ttyUSB0",O_RDWR | O_NOCTTY);    /* ttyUSB0 is the FT232 based USB2SERIAL Converter   */
                                /* O_RDWR Read/Write access to serial port           */
                                /* O_NOCTTY - No terminal will control the process   */


        if(fd == -1)                        /* Error Checking */
               printf("\n  Error! in Opening ttyUSB0  ");
        else
               printf("\n  ttyUSB0 Opened Successfully ");


    /*---------- Setting the Attributes of the serial port using termios structure --------- */

    struct termios SerialPortSettings;  /* Create the structure                          */

    tcgetattr(fd, &SerialPortSettings); /* Get the current attributes of the Serial port */

    cfsetispeed(&SerialPortSettings,B4800); /* Set Read  Speed as 9600                       */
    cfsetospeed(&SerialPortSettings,B4800); /* Set Write Speed as 9600                       */

    SerialPortSettings.c_cflag &= PARENB;   /* Disables the Parity Enable bit(PARENB),So No Parity   */
    SerialPortSettings.c_cflag &= ~CSTOPB;   /* CSTOPB = 2 Stop bits,here it is cleared so 1 Stop bit */
    SerialPortSettings.c_cflag &= ~CSIZE;    /* Clears the mask for setting the data size             */
    SerialPortSettings.c_cflag |=  CS7;      /* Set the data bits = 8                                 */

    SerialPortSettings.c_cflag &= ~CRTSCTS;       /* No Hardware flow Control                         */
    SerialPortSettings.c_cflag |= CREAD | CLOCAL; /* Enable receiver,Ignore Modem Control lines       */ 


    SerialPortSettings.c_iflag &= ~(IXON | IXOFF | IXANY);          /* Disable XON/XOFF flow control both i/p and o/p */
    SerialPortSettings.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG);  /* Non Cannonical mode                            */

    SerialPortSettings.c_oflag &= ~OPOST;/*No Output Processing*/

    /* Setting Time outs */
    SerialPortSettings.c_cc[VMIN] =  1; /* Read at least 10 character */
    SerialPortSettings.c_cc[VTIME] = 0;  /* Wait indefinetly   */

    if((tcsetattr(fd,TCSANOW,&SerialPortSettings)) != 0) /* Set the attributes to the termios structure*/
        printf("\n  ERROR ! in Setting attributes");
    else
                printf("\n  BaudRate = 9600 \n  StopBits = 1 \n  Parity   = none");

    /*---------------------------------------- Controlling RTS and DTR Pins --------------------------------------*/
    /* ~RTS(USB2SERIAL) ---> ~RE(MAX485) */
    /* ~DTR(USB2SERIAL) --->  DE(MAX485) */

    /*------------------------- Putting MAX485 chip in USB2SERIAL in Transmit Mode ---------------------------*/
    //                                                                                                        //
    //  ----+           +-----------+              H  +-----------+                                           //
    //      |           |       ~RTS| --------------> |~RE        |                                           //
    //   PC |==========>| FT232     |                 |   MAX485  +(A,B)~~~~~~~~~~~~~~~>Data out(RS485)       //
    //      |    USB    |       ~DTR| --------------> | DE        |        Twisted Pair                       //
    //  ----+           +-----------+              H  +-----------+                                           //
    //                                                                                                        //
    //--------------------------------------------------------------------------------------------------------//
    //TxMode - DE->High,~RE -> High

    int RTS_flag,DTR_flag;

    RTS_flag = TIOCM_RTS;   /* Modem Constant for RTS pin */
    DTR_flag = TIOCM_DTR;   /* Modem Constant for DTR pin */

    ioctl(fd,TIOCMBIC,&RTS_flag);/* ~RTS = 1,So ~RE pin of MAX485 is HIGH                       */
    ioctl(fd,TIOCMBIC,&DTR_flag);/* ~DTR = 1,So  DE pin of MAX485 is HIGH,Transmit Mode enabled */ 

        /*------------------------------- Write data to serial port -----------------------------*/

    tcflush(fd, TCIFLUSH);   /* Discards old data in the rx buffer            */        

    char write_buffer[] = "///?01!";    /* Buffer containing characters to write into port       */ 
    char write_buffer1[] = {'\r','\n'};
    int  bytes_written  = 0;    /* Value for storing the number of bytes written to the port */ 

    bytes_written = write(fd,write_buffer,7);/* use write() to send data to port                                            */
                                     /* "fd"                   - file descriptor pointing to the opened serial port */
                                     /* "write_buffer"         - address of the buffer containing data              */
                                     /* "sizeof(write_buffer)" - No of bytes to write                               */  
    printf("\n  %s written to ttyUSB0",write_buffer);

    bytes_written = write(fd,write_buffer1,2);/* use write() to send data to port                                            */
                                     /* "fd"                   - file descriptor pointing to the opened serial port */
                                     /* "write_buffer"         - address of the buffer containing data              */
                                     /* "sizeof(write_buffer)" - No of bytes to write                               */  
    printf("\n  %s written to ttyUSB0",write_buffer);
    printf("\n  %d Bytes written to ttyUSB0", bytes_written);
    printf("\n +----------------------------------+\n\n");

    char buf[20000];
        sleep(2); 
    while(1)
    {

    printf("tring to read port\n");
       int res = read(fd,buf,1);

sleep(1);
    printf("%c  :: %d\n",buf[0],res);   

}
    printf("\n +----------------------------------+\n\n\n");
    close(fd); /* Close the serial port */

    }

--------------------------------------------------------

Setting for running the code :BAUD RATE is 4800 Databits is 7 , Parity is EVEN, and Stopbit is 1.

If i compile the code and run it is not working. Before running the code if i open and close the minicom with BAUD B4800 & 7E1 then my code is working. Can any one suggest where is the problem why it is not working.

  • 1
    *"Not working"* is not a meaningful or helpful description of what goes wrong with your program. Your program has many statements which have conflicting comments. That's sloppy coding that needs to be cleaned up. Return codes from syscalls are not properly checked. There are several termios errors relating to parity and canonical configuration . But the most serious issue is that you only manipulate the RS-485 control lines one time, whereas I would expect these control lines to be toggled between read and write modes for proper half-duplex operation. – sawdust Aug 28 '18 at 20:14
  • Facing similar issue. Have you found any solution? – abhiarora Nov 07 '19 at 07:10

0 Answers0