
Arduino Quick Start
ToughC5 RS485 communication example program.
3.3.9M5ToughC50.2.220.2.28#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);
// ESP32-C5 GPIO23=RX, GPIO24=TX on the ToughC5 M5BUS
Serial1.begin(115200, SERIAL_8N1, 23, 24);
}
void loop() {
M5.update();
// --- Send Data ---
String msg = "RS485 #" + String(++cnt);
Serial1.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 (Serial1.available()) {
char ch = Serial1.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 program sends a data packet through the RS485 interface every 2 seconds while listening for and receiving data over the same interface. You can view the transmitted and received data in the serial monitor and on the device display. The program uses the Serial2 object to configure and operate the RS485 interface. You can change the data content and transmission interval as needed.
The Tough RS485 interface is on the Tough Ext Board. It is the green port, as shown below:
The example output is shown below:
