RS-485 USB для RS485 C код - PullRequest
       28

RS-485 USB для RS485 C код

0 голосов
/ 28 августа 2018
#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 */

    }

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

Настройка для запуска кода: BAUD RATE равен 4800, бит данных равен 7, четность равна EVEN, а стоп-бит равен 1.

Если я скомпилировал код и запустил его, он не работает. Перед запуском кода, если я открываю и закрываю миником с BAUD B4800 & 7E1, тогда мой код работает. Кто-нибудь может подсказать, в чем проблема, почему она не работает.

...