pdf-icon

Arduino 上手教程

2. 设备开发 & 案例程序

6. 应用案例

PowerHub RS485

PowerHub RS485 通信相关 API 与案例程序。

案例程序

编译要求

  • M5Stack 板管理版本 >= 3.2.3
  • 开发板选项 = M5PowerHub
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
#include <Arduino.h>

HardwareSerial& RS485 = Serial2;

const int MCU_485_DIR = 18;
const int MCU_485_TXD = 8;
const int MCU_485_RXD = 17;

void setup() {
  Serial.begin(115200);

  pinMode(MCU_485_DIR, OUTPUT);
  digitalWrite(MCU_485_DIR, LOW);
  RS485.begin(115200, SERIAL_8N1, MCU_485_RXD, MCU_485_TXD);
  Serial.println("\nRS485 ready. ");
}

void loop() {
  // transmit
  const char* tx_msg = "Hello RS485\r\n";  // change it on another device
  digitalWrite(MCU_485_DIR, HIGH);
  delay(10);
  RS485.print(tx_msg);
  RS485.flush();
  Serial.println("TX OK");
  digitalWrite(MCU_485_DIR, LOW);

  // receive (non-blocking)
  while (RS485.available()) {
    int rx = RS485.read();
    Serial.write(rx);
  }

  delay(2000);
}

准备两个 PowerHub,刷入以上代码(可修改消息内容以作区分),将两者的 120 Ω 终端匹配电阻开关置于 ON,然后用 VH3.96-4P 接口的连接线(比如 Shielded Twisted Pair Cable)连接两个设备的 RS485 接口:

连接后,两个 PowerHub 将互相通过 RS485 发送消息。将其中一个连接到电脑,观察串口输出:

API

PowerHub RS485 通信部分驱动使用了 Arduino 自带的 HardwareSerial 硬件串口通讯,更多相关的 API 可以参考下方文档:

On This Page