pdf-icon

Arduino Quick Start

2. Devices & Examples

6. Applications

Tough RS485 Communication

Tough RS485 communication example program.

Example Program

Compilation Requirements

  • M5Stack Board Manager Version >= 2.1.4
  • Board Selection = M5Tough
  • M5Unified Library Version >= 0.2.5
  • M5GFX Library Version >= 0.2.7
cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#include <M5Unified.h>
#include <M5GFX.h>

static int cnt = 0;          // Counter for RS485 sent messages (increments per transmission)
String recvBuffer;           // Buffer to store received RS485 data

void setup() {
    M5.begin();           
    M5.Display.clear();  
    M5.Display.setFont(&fonts::FreeMonoBold9pt7b); 
    M5.Display.drawString("Send :", 5, 5);     
    M5.Display.drawString("Receive :", 5, 125);  
    
    Serial.begin(115200);   
    
    // Parameters: baud rate=115200, config=8N1 (8 data bits, 1 stop bit, no parity), RX pin=27, TX pin=19
    Serial2.begin(115200, SERIAL_8N1, 27, 19);
}

void loop() {
    M5.update();         

    // --- Send Data ---
    String msg = "RS485 #" + String(++cnt); 
    Serial2.println(msg);          
    Serial.printf("Send: %s\n", msg.c_str());

    // Display sent message on screen
    M5.Display.fillRect(0, 25, 320, 30, TFT_BLACK); 
    M5.Display.setTextColor(GREEN);   
    M5.Display.setCursor(20, 25);             
    M5.Display.printf("%s\n", msg.c_str());       

    // --- Receive Data ---
    recvBuffer = "";                  
    while (Serial2.available()) {         
        char ch = Serial2.read();            
        recvBuffer += ch;                       
    }

    // If valid data is received
    if (recvBuffer.length() > 0) {
        Serial.print("Recv: ");                  
        Serial.print(recvBuffer);
        
        // Display received message on screen
        M5.Display.setTextColor(YELLOW);       
        M5.Display.fillRect(0, 145, 320, 30, TFT_BLACK); 
        M5.Display.setCursor(20, 145);            
        M5.Display.printf("%s", recvBuffer.c_str()); 
    }

    delay(2000); 
}

The main function of this program is to send a data packet via the RS485 interface every 2 seconds, while simultaneously listening for and receiving data transmitted through the same RS485 interface. Users can view both the transmitted and received data via the serial monitor and the main control screen.
The Serial2 object is used in the program to configure and operate the RS485 interface, with settings of a baud rate of 115200, 8 data bits, 1 stop bit, and no parity check.
Users can modify the data content and transmission frequency as needed.

The RS485 interface of the M5Tough is located on the Tough Ext Board, marked with a green port, as shown in the image below:

The effect of the example is shown as follows:

On This Page