UART-485 Communication Guide: Wireless Dialogue Between MCU and PLC

UART-485 Communication Guide: Wireless Dialogue Between MCU and PLC

Hello everyone, I am Da Yi! Today we will talk about a very practical topic: UART-485 communication. This technology allows microcontrollers and PLCs to communicate wirelessly, just like two people conveniently chatting via video call on their phones. Have you ever wondered how mobile phones achieve wireless communication?
Let’s start with an example from our daily lives. For instance, when you are cooking in the kitchen and want your partner in the living room to help turn on the TV to check the latest weather report. You certainly wouldn’t want to shout loudly and scare your partner, nor would you run to the living room to press the remote control directly. The simplest way would be to just make a phone call.
UART-485 communication is like a “wireless phone” between microcontrollers and PLCs. It is built on the foundation of serial communication, featuring a relatively long transmission distance and strong anti-interference capability. Let’s start from the basics of UART serial ports.

UART Serial Communication

UART stands for “Universal Asynchronous Receiver/Transmitter”. It provides full-duplex communication between microcontrollers and external devices, just like when you and I can talk and hear each other’s voices simultaneously on a phone call.
In UART communication, the sender first converts parallel data into a serial data stream that is sent out. The receiver is responsible for reassembling the received data stream into parallel data. The entire process is completed through a single data line plus a ground line, just like a regular headphone cable that only has two wires.
[UART Communication Principle Diagram](https://upload-images.jianshu.io/upload_images/1776336-0afebd26be570d47.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
Each frame of data contains a start bit, data bits, an optional parity bit, and a stop bit. Both parties must agree on parameters such as baud rate, data bit length, and parity bit settings to correctly interpret the messages sent by each other.
Next, let’s see how to use UART on a microcontroller:

#include <reg51.h>

void UART_Init() 
{
  TMOD = 0x20; // Timer 1 works in mode 2
  TH1 = 0xFD;  // Calculate baud rate
  SCON = 0x50; // Set working mode
  TR1 = 1;     // Start timer
}

void UART_SendByte(unsigned char dat)
{
  SBUF = dat;      // Write sending data
  while(!TI);      // Wait for sending to finish  
  TI = 0;          // Clear sending interrupt flag
}

unsigned char UART_ReceiveByte()
{
 unsigned char dat;
 while(!RI);       // Wait for reception to finish
 dat = SBUF;       // Read received data
 RI = 0;           // Clear receiving interrupt flag
 return dat;
}

With the basics of UART, we can extend to the more powerful RS-485 communication protocol. First, we need a 485 transceiver chip, such as the common SP485 or SP3485. They integrate two independent circuits for sending and receiving, supporting half-duplex communication.
[485 Transceiver Circuit](https://upload-images.jianshu.io/upload_images/1776336-3de0f8f2caf03aa1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
When the microcontroller/PLC pulls the “send enable” pin of this chip high, the sending data is sent through the A and B lines, and the terminal resistor connects the signal line to ground. For receiving, the microcontroller simply pulls the TE pin low.
The RS-485 network can support up to 32 nodes simultaneously, with a theoretical maximum transmission distance of 1200 meters. However, in engineering practice, it is advisable to keep it within a few hundred meters and limit the number of nodes to below 16 for safety.
We can also add repeaters and hubs on the RS-485 bus to achieve larger-scale and more complex communication networks. However, we must also pay attention to wiring quality and grounding issues to prevent communication failures.
485 communication is half-duplex, meaning only one device can send at a time while the others are in receiving mode. To coordinate the sending order, we need a communication protocol, acting like a referee to maintain order.
Simple applications can use a query-response mode. The master microcontroller sends a query command, and the slave PLC or other microcontroller responds with the corresponding data. More intelligent technologies also include broadcast addressing, message frame structure definition, error checking, etc.
However, these topics are a bit beyond the scope, and interested friends can explore the operation principles of the MODBUS protocol on their own. Here’s a simple RS485 example program:

/* Master Query Code */
// Set master address
#define HOST_ADDR   0x01

void UART_SendPacket(unsigned char addr, unsigned char cmd, unsigned char *dat, unsigned char len)
{
  unsigned char sum = 0;
  UART_SendByte(':');
  UART_SendByte(addr);
  UART_SendByte(cmd);
  UART_SendByte(len);
  for(i = 0; i < len; i++)
  {
    UART_SendByte(dat[i]);
    sum += dat[i];
  }
  UART_SendByte(sum);
}

void main()
{
  unsigned char dat[8]; 
  UART_Init();
  UART_SendPacket(0x02, 0x03, dat, 8); // Query data from slave 2
  for(i = 0; i < 8; i++)
  {
    dat[i] = UART_ReceiveByte();  // Receive response data from slave
  }
}

/* Slave Response Program */
#define SLAVE_ADDR   0x02   
unsigned char cmd, len, sum;
unsigned char dat[8];

void ProcessCommand()
{
  sum = 0;
  cmd = UART_ReceiveByte();
  len = UART_ReceiveByte();
  for(i = 0; i < len; i++) 
  {
    dat[i] = UART_ReceiveByte();
    sum += dat[i];
  }
  sum += UART_ReceiveByte();  // Read checksum
  
  if(sum == 0) // No error, process command
  {
     ...
     UART_SendResponse(dat, len); // Send response data
  }
}

void main()
{
  UART_Init();
  while(1)
  {
    if(UART_ReceiveByte() == ':')
    {
      if(UART_ReceiveByte() == SLAVE_ADDR)
        ProcessCommand();
    }
  }
}

This example is just a simple communication architecture. In actual projects, you may need to consider more details, such as:

  • Power Failure Protection: How to protect data when power is cut off? You can use EEPROM or battery backup.
  • Multi-Master Conflict: How to handle conflicts when multiple masters send commands simultaneously?
  • Online Upgrade: How to remotely upgrade device firmware using the serial port?
  • Encryption Mechanism: Data involving commercial secrets and personal privacy needs to be transmitted securely.
  • Communication Delay: How long does it take for a query command to complete round-trip communication?

Of course, the most interesting are the various “unexpected” situations encountered in real projects. This requires us to have a certain level of debugging and maintenance experience. For example, incorrect wiring on-site causing equipment damage, communication lines chewed by mice, communication chips overheating and malfunctioning after long-term operation, etc.
Therefore, my advice is to practice more hands-on and develop a habit of paying attention to details. Don’t think that everything is fine just because you simulated communication at home; remember to be particularly careful during on-site debugging.
Alright everyone, that’s all for my guide. If you have any unclear points, feel free to continue asking me questions. I will keep adding and refining this guide to ensure that beginners can steadily and practically master the wireless dialogue technology between microcontrollers and PLCs!

Leave a Comment