rs-485 USB至RS485 C代码

时间:2018-08-28 14:13:23

标签: serial-port rs485

#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打开和关闭小型通信,则我的代码有效。 任何人都可以提出问题所在,为什么它不起作用。

0 个答案:

没有答案