pdf-icon

Arduino Quick Start

2. Devices & Examples

6. Applications

Hat RS485 Arduino Tutorial

1. Preparation

2. Example Program

Case Description
Hat RS485 is an RS485 converter compatible with M5StickC. It integrates an SP485EEN chip and mainly consists of an RS485 automatic transceiver circuit and a DC-DC buck circuit (which can step down the input voltage to 5V). This product is used to convert TTL signals into RS485 signals, enabling communication between different devices. In this example, two StickC-Plus2 units, a pair of shielded twisted pair cables, and two Hat RS485 modules are used for connection. The two Hat RS485 modules send data to each other via TX and RX interfaces, and the received data will be displayed on the StickC-Plus2 screen as well as on the computer serial monitor.

Complete Program

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
#include <M5Unified.h>

void setup() {
  // Initializatization
  auto cfg = M5.config();
  M5.begin(cfg);
  // Serial2.begin(unsigned long baud, uint32_t config, int8_t rxPin, int8_t txPin, bool invert)
  Serial2.begin(9600, SERIAL_8N1, 26, 0);   // (RX: G26, TX: G0)
  Serial.begin(115200);

  // setup display
  M5.Display.setRotation(1);
  M5.Display.fillScreen(BLACK);
  M5.Display.setTextColor(ORANGE);
  M5.Display.setTextSize(2);
  M5.Display.setCursor(0, 10);
  M5.Display.println("RS485 message:");
}

void loop() {
  M5.update();
  if (M5.BtnA.wasClicked()) {     // Click StickC-Plus2 Button A to send data
    Serial.println("RST485 sent: Hello M5Stack!");
    Serial2.println("Hello M5Stack!");
  }
  if (Serial2.available()) {      // Received data and display on StickC-Plus2's screen
    char ch = Serial2.read();
    M5.Display.setTextColor(CYAN);
    M5.Display.setTextSize(2);
    M5.Display.print(ch);
  }
  delay(10);
}

3. Compile and Upload

  1. Enter download mode: Before uploading programs to different Stick devices, you need to install the corresponding driver. The required driver and installation procedure may vary with different controllers. Refer to the bottom section of the Arduino IDE Getting Started Tutorial page for detailed steps based on your specific device.

  2. Select the device port, click the “Verify & Upload” button in the top left corner of Arduino IDE, and wait for the program to compile and upload to the device.

  1. After the program has been compiled and uploaded to the first StickC device, upload the same program to the second StickC device.

4. Data Transmission Between Hat RS485 Devices

This program will use the TX and RX interfaces of Hat RS485 to send data to each other (press ButtonA on StickC-Plus2 to send data). The transmitted data will be displayed on the screen of StickC-Plus2 and printed on the computer’s serial monitor:

On This Page