RS485 is a standard for long-distance data transmission. Its basic usage is the same as that of a serial port, that is, defining RX and TX ports, communication baud rate, and data bits for communication. Typically, it is configured as (9600, Serial_8N1, RX_PIN, TX_PIN), with a baud rate of 9600, 8 data bits, no parity bit, and 1 stop bit.
Serial2.begin(115200, SERIAL_8N1, RX_PIN, TX_PIN);
Serial2.print("97"); or Serial2.write("97");
if(Serial2.available()){ char c = Serial2.read(); }
*The following basic code is for reference only
#include <M5Stack.h>
#define RX_PIN 16
#define TX_PIN 17
void setup() {
M5.begin();
Serial2.begin(9600, SERIAL_8N1, RX_PIN, TX_PIN); // Initialize Serial2
}
void loop() {
if(M5.BtnA.wasPressed()){ // If button A is pressed
Serial2.print("hello,from RS485\r\n"); // Send data through Serial2
}
if(Serial2.available()){ // If there is data to read from Serial2, read and print it
char c = Serial2.read();
Serial.print(c);
}
M5.update(); // Refresh button state
}
Example of using RS485 with UIFlow
For specific details, refer to the RS485 example. Below is the demonstration code
#include <M5Stack.h>
#define RX_PIN 16
#define TX_PIN 17
#define X_LOCAL 40
#define Y_LOCAL 40
#define X_OFF 160
#define Y_OFF 30
int distance = 0; // The stepping value for the stepper motor movement
void header(const char *string, uint16_t color){ // Header
M5.Lcd.fillScreen(color);
M5.Lcd.setTextSize(1);
M5.Lcd.setTextColor(TFT_MAGENTA, TFT_BLUE);
M5.Lcd.fillRect(0, 0, 320, 30, TFT_BLUE);
M5.Lcd.setTextDatum(TC_DATUM);
M5.Lcd.drawString(string, 160, 3, 4);
}
void setup() {
M5.begin();
M5.Power.begin();
header("PUSH 6060", TFT_BLACK);
M5.Lcd.setTextFont(2);
M5.Lcd.setTextColor(TFT_WHITE, TFT_BLACK);
Serial2.begin(9600, SERIAL_8N1, RX_PIN, TX_PIN); // Configure Serial2
delay(500);
Serial2.print("ID=123\r\n"); // Output ID=123\r\n through Serial2, setting the motor ID to 123
}
void loop() {
if
(M5.BtnA.wasPressed()){ // Press button A to send ID\r\n, to check the motor ID
Serial2.print("ID\r\n");
}
if(M5.BtnB.wasPressed()){ // Press button B to send ID123:X%d\r\n to control absolute movement distance, where %d is the variable distance
if(distance < 50){
distance +=10;
Serial2.printf("ID123:X%d\r\n",distance);
}
}
if(M5.BtnC.wasPressed()){ // Press button C to send ID123Z\r\n, motor returns to the origin
Serial2.print("ID123Z\r\n");
}
if(Serial2.available()){ // Receive and print messages returned by the motor through Serial2
char c = Serial2.read();
Serial.print(c);
}
M5.update();
}