Single chip microcomputer RS485 communication interface, control line, schematic diagram and program example

Source: Internet
Author: User
The RS232 standard was born before RS485, but there are several deficiencies in RS232: The signal level of the interface is higher, to more than 10 V, the use of improper easy to damage the interface chip, level standard is also incompatible with the TTL level. Transmission rate is limited, can not be too high, generally to zero or zero bits per second (kb/s) to the limit. The interface uses signal lines and GND to form a common mode of communication with other devices, and this co-mode transmission is prone to interference and has a weaker anti-jamming performance. The transmission distance is limited and can only communicate up to dozens of meters. Communication can only be communicated between two points, not to achieve multi-machine networking communication.
For the shortcomings of the RS232 interface, there are a number of new interface standards, RS485 is one of them, it has the following characteristics: the use of differential signals. When we talk about A/d, we talk about the concept of differential signal input and the benefits of differential input, and the biggest advantage is the ability to suppress common-mode interference. Especially when the industrial site environment is more complex, the interference is more long, the use of differential mode can effectively improve the communication reliability. The RS485 uses two communication lines, usually expressed in A and B or d+ and D. The logic "1" is expressed as a voltage difference of + (0.2~6) v between the two lines, and the logic "0" is a typical differential communication represented by a voltage difference of-(0.2~6) v between the two lines. RS485 communication rate is fast, the maximum transmission speed can reach more than 10mb/s. The internal physical structure of the RS485 is based on a combination of a balanced driver and a differential receiver, and the ability to resist interference is greatly increased. Transmission distance of up to 1200 meters, but its transmission rate and transmission distance is inversely proportional, only in the 100kb/s below the transmission speed, can reach the maximum communication distance, if the need to transfer more distance can use relay. Can be networked on the bus to achieve multi-machine communication, the bus allows to hang a plurality of transceivers, from the existing RS485 chip, can be hung 32, 64, 128, 256 and other devices of different drives. The interface of the RS485 is very simple, similar to the MAX232 used by RS232, only requires a RS485 converter, it can be directly connected with the UART serial port, and the use of the same asynchronous serial communication protocol. However, since RS485 is a differential communication, it is not possible to receive data and send data simultaneously, which means that it is a half-duplex communication. So how do we determine when to send and when to receive it?
RS485 conversion chip A lot, this lesson we take the typical MAX485 as an example to explain RS485 communication, as shown in Figure 18-1.
Figure 18-1 MAX485 Hardware interface
MAX485 is a popular RS485 converter introduced by Maxim. Where 5 feet and 8 feet are power pins, 6 feet and 7 feet is a and B two pins in RS485 communication, 1 feet and 4 feet are received on the RXD and txd pins of MCU, and the data receive and transmit directly using the single chip microcomputer UART; 2 feet and 3 feet are the direction pins, where 2 feet is a low-level enable receiver, 3 feet is a high-level enable output driver, we put these two pins together, usually do not send the data, keep the two pins is low, let MAX485 in the receiving State, when the need to send data, pull this pin high, send data, After sending it, pull the pin down. In order to improve the anti-jamming ability of the RS485, it is necessary to connect a resistor between the A and B pins near the MAX485, which can be a resistance value from 100 Kohm to 1K.

Here we also introduce how to use the KST-51 single-chip microcomputer development Board for peripheral expansion experiments. Our Development Board can only be the basic function for the students to do out to provide experimental practice, but the students learn the footsteps should not stay on the board. If you want to do more experiments, you can expand the experiment by expanding the interface of the single-chip microcomputer development Board. You can see the blue-green single-chip frame around the 32 pins, these 32 pins is the microcontroller's 32 IO pins are all cited out. The schematic shows that the J4, J5, J6, J7 4 devices, as shown in Figure 18-2.
Figure 18-2 Single-chip microcomputer expansion interface
Not all of these 32 IO ports can be used for external expansion, which is not available as data output and as a pin for data input, such as P3.2, P3.4, P3.6 pins, which are not available for the three pins. For example P3.2 this pin, if we use to expand, send the signal if and ds18b20 timing, will cause DS18B20 pull low pin, affect communication. In addition to the 29 of the 3 IO ports, you can use the DuPont wire to connect the pins and expand them. Of course, if the current IO port is applied to the expansion function, the corresponding function on the board can not be realized, that is, the need to expand the function and the onboard function between two choices.

In the RS485 experiment, our communication pins must be P3.0 and P3.1, in addition to a directional control pin, we use the DuPont line to connect it to the P1.7. The other end of the RS485, you can use a USB to RS485 module, with twisted pair of the Development Board and the module A and B respectively connected together, the USB plug into the computer, and then you can communicate.

After learning the 13th chapter practical serial communication method and program, do this serial communication method is very simple, the basic is consistent. We use the idea of a practical serial communication routine, do a simple program, through the serial debugging assistant issued any character, the microcontroller received after the end of the Add "carriage return + line break" after the return, in the debugging assistant re-display, first put out the program.

One thing to note in the program is that because the MAX485 is usually set to receive state, the MAX485 is changed to send state only when the data is sent, so the MAX485 direction pin is pulled high at the beginning of the Uartwrite () function, and the function is pulled down before exiting. But here is a detail, that is, the single-chip transmission and receive interrupt generation is half of the stop bit, that is, every time the stop bit transmission half of the time, RI or TI has been set and immediately into the interrupt (if the interrupt is enabled) function, receive the time naturally no problem, But it's different when it's sent: When a byte of data is written to Sbuf, the UART hardware starts sending the new byte after the last stop bit has been sent, but if it does not continue sending the next byte, it is already sent, stop sending and pull the MAX485 direction pin down so MAX485 back in the receiving State when there is a problem, because this time the last stop bit actually sent only half, not fully completed, so there is the Uartwrite () function within the DELAYX10US (5) This operation, which is artificially increased 50us delay, this 50US Time just to make the rest of the stop bit complete, then this time is naturally determined by the communication baud rate, half the baud rate cycle.

/****************************RS485.C File Program source code *****************************/

#include <reg52.h> #include <intrins.h> sbit rs485_dir = p1^7; RS485 Direction selector pin bit flagframe = 0; The frame receives the completion flag, that is, receives a frame new data bit flagtxd = 0; Single byte send completion flag, used to replace TXD interrupt flag bit unsigned char cntrxd = 0; Receive byte counter unsigned char pdata bufrxd[64];

Receive byte buffer extern void uartaction (unsigned char *buf, unsigned char len); /* Serial configuration function, baud-communication baud rate */void Configuart (unsigned int baud) {rs485_dir = 0;//rs485 set to receive direction SCON = 0x50;//configure serial port as mode 1 Tmod &= 0x0F; Clear 0 T1 control bit tmod |= 0x20; Configure T1 for mode 2 TH1 = 11059200/12/32)/baud; Computes the T1 overloaded value TL1 = TH1; The initial value equals the overloaded values ET1 = 0; Prohibit T1 interrupt ES = 1; Enable serial port Interrupt TR1 = 1;
        Start T1}/* Software delay function, delay time (T*10) US */void delayx10us (unsigned char t) {do {_nop_ ();
        _nop_ ();
        _nop_ ();
        _nop_ ();
        _nop_ ();
        _nop_ ();
        _nop_ ();
    _nop_ ();
} while (--T); }/* Serial data write, that is, serial send function, buf-to send the data pointer, len-the specified send length */void Uartwrite (unsigned char *buf, unsigned char len) {rs485_dir = 1; //RS485 set to send while (len--) {///loop all bytes Flagtxd = 0;//Clear 0 Send flag sbuf = *buf++;//Send a Byte data whil E (!FLAGTXD); Wait for the byte to send complete} delayx10us (5); Wait for the last stop bit to complete, the delay time is determined by the baud rate Rs485_dir = 0; RS485 set to receive}/* Serial data read function, buf-receive pointer, len-specified read length, return value-Actual read length */unsigned char uartread (unsigned char *buf, unsigned char l
    EN) {unsigned char i;
    Specifies that the read length is greater than the actual received data length,//The read length is set to the actual received data length if (Len > cntrxd) {len = Cntrxd;
    } for (i=0; i<len; i++) {//copy received data to receive pointer on *buf++ = Bufrxd[i]; } cntrxd = 0; Receive counter clear 0 return len; return actual read length}//serial receive monitoring, by idle time decision frame end, need to call in a timed interrupt, ms-timed interval */void Uartrxmonitor (unsigned char ms) {static unsigned char CNTB
    KP = 0;
   
    static unsigned char IDLETMR = 0; if (Cntrxd > 0) {//Receive counter is greater than zero, monitor bus idle time if (CNTBKP! = cntrxd) {//Receive counter changes, when data is just received, clear 0 idle timing CNTBKP = CNT
            Rxd;
        IDLETMR = 0; }else{//Receive counter unchanged, i.e. when bus idle, cumulative idle time if (IDLETMR < 30) {//Idle timingLess than 30ms, continuous accumulation idletmr + = ms;
            if (IDLETMR >= 30) {//Idle time reaches 30ms, that is, a frame is determined to receive the complete flagframe = 1;//Set frame receive completion flag}
    }}}else{CNTBKP = 0;
    }////serial driver function, monitor data frame receive, dispatch function function, need to call in the main loop */void Uartdriver () {unsigned char len;
   
    unsigned char pdata buf[40];
        if (flagframe) {//has a command arrives, read processing the command flagframe = 0; Len = Uartread (buf, sizeof (BUF)-2); Reads the received command into the buffer uartaction (buf, Len); Pass data frame, invoke action execution function}//serial Interrupt service function */void Interruptuart () interrupt 4{if (RI) {//Receive new byte RI = 0;//Clear 0 receive interrupt flag
        Bit//When the receive buffer is not exhausted, save the receive byte and increment the counter if (Cntrxd < sizeof (BUFRXD)) {bufrxd[cntrxd++] = Sbuf; }} if (TI) {//bytes sent complete ti = 0;///Clear 0 Send interrupt flag bit FLAGTXD = 1;//Set Byte send completion flag}}


/*****************************MAIN.C File Program source code ******************************/

#include <reg52.h> unsigned char t0rh = 0; T0 High-byte unsigned char T0RL = 0 for overloaded values;
T0 the low-byte void ConfigTimer0 (unsigned int ms) of the overloaded value;
extern void Uartdriver ();
extern void Configuart (unsigned int baud);
extern void Uartrxmonitor (unsigned char ms);

extern void Uartwrite (unsigned char *buf, unsigned char len);
        void Main () {EA = 1;//Open Total Interrupt ConfigTimer0 (1);//Configure T0 Timing 1ms configuart (9600);//configure baud rate to 9600 while (1) { Uartdriver (); Call the serial driver}///serial action function to perform a response based on the received command frame buf-the command frame pointer received, len-command frame length */void uartaction (unsigned char *buf, unsigned char l
    EN) {//After the received data frame is added after the change of the line character and sent back to buf[len++] = ' \ r ';
    buf[len++] = ' \ n ';
Uartwrite (buf, Len); }/* Configure and start t0,ms-t0 timing time */void ConfigTimer0 (unsigned int ms) {unsigned long tmp;//TEMP variable TMP = 11059200/12;//fixed Timer count Frequency TMP = (TMP * ms)/1000; Calculates the required count value of TMP = 65536-TMP; Calculates the timer reload value TMP = tmp + 33; Compensating for interrupt response delay Error T0RH = (unsigned char) (TMP&GT;&GT;8); The timer reload value is split into high and low byte T0RL = (unsigned chAR) tmp; Tmod &= 0xF0; Clear 0 T0 control bit tmod |= 0x01; Configure T0 for mode 1 TH0 = T0RH;
    Load T0 overloaded value TL0 = T0RL; ET0 = 1; Enable T0 Interrupt TR0 = 1;
    Start T0}/* T0 interrupt service function, perform serial receive monitoring */void InterruptTimer0 () interrupt 1{TH0 = T0RH;//Reload load value TL0 = T0RL; Uartrxmonitor (1); Serial receiver Monitoring}


Now look at this serial program, is not feeling very simple it. Serial Communication program We use repeatedly, coupled with the learning module more and more, practice more and more, the original feeling very complex things, now will feel simple. From the Device Manager can see all the COM number, we download the program with COM4, and the USB to RS485 virtual is COM5, communication when we use the COM5 port, as shown in Figure 18-3.
Figure 18-3 RS485 Communication test setup and results

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.