Skip to content

Instantly share code, notes, and snippets.

@maxpromer
Created January 30, 2024 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxpromer/127d5eaf34e10fb9bbba6f9986213efd to your computer and use it in GitHub Desktop.
Save maxpromer/127d5eaf34e10fb9bbba6f9986213efd to your computer and use it in GitHub Desktop.
#include <ModbusMaster.h>
#define RS485_RX_PIN (15)
#define RS485_TX_PIN (17)
#define RS485_DIR_PIN (16)
ModbusMaster sensor;
void preTransmission() {
digitalWrite(RS485_DIR_PIN, HIGH);
}
void postTransmission() {
digitalWrite(RS485_DIR_PIN, LOW);
}
void setup() {
Serial.begin(115200);
pinMode(RS485_DIR_PIN, OUTPUT);
digitalWrite(RS485_DIR_PIN, LOW);
// Modbus communication runs at 9600 baud
Serial2.begin(9600, SERIAL_8N1, RS485_RX_PIN, RS485_TX_PIN); // AdapBit
// XY-MD02 init with Modbus slave ID 1
sensor.begin(1, Serial2);
sensor.preTransmission(preTransmission);
sensor.postTransmission(postTransmission);
}
void loop() {
// XY-MD02 read
uint8_t result;
result = sensor.readInputRegisters(1, 2); // Read Input Register start at 1 -> 2 word (0x0001 - 0x0002)
if (result == sensor.ku8MBSuccess) {\
float temp_c = sensor.getResponseBuffer(0) / 10.0;
float humi_rh = sensor.getResponseBuffer(1) / 10.0;
Serial.println("Temp: " + String(temp_c, 1) + " *C\tHumi: " + String(humi_rh, 1) + " %RH");
delay(100);
} else {
Serial.println("Read XY-MD02 error, check your serial configs, wiring and power supply");
delay(1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment