Last active
December 5, 2024 04:26
-
-
Save maxpromer/1d2b64191f51e2d8bd6bb14e5d0d56b6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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(4800, SERIAL_8N1, RS485_RX_PIN, RS485_TX_PIN); // AdapBit | |
| // Sensor init with Modbus slave ID 1 | |
| sensor.begin(1, Serial2); | |
| sensor.preTransmission(preTransmission); | |
| sensor.postTransmission(postTransmission); | |
| } | |
| void loop() { | |
| // Read | |
| uint8_t result; | |
| result = sensor.readInputRegisters(0, 7); // Read Input Register start at 0 -> 7 word (0x0000 - 0x0006) | |
| if (result == sensor.ku8MBSuccess) { | |
| float soil = sensor.getResponseBuffer(0) / 10.0; | |
| float temp = sensor.getResponseBuffer(1) / 10.0; | |
| int ec = sensor.getResponseBuffer(2); | |
| float ph = sensor.getResponseBuffer(3) / 10.0; | |
| int n = sensor.getResponseBuffer(4); | |
| int p = sensor.getResponseBuffer(5); | |
| int k = sensor.getResponseBuffer(6); | |
| Serial.printf("Soil: %.01f %%\tTemp: %.01f *C\tEC: %d\tPH: %.01f\tN: %d\tP: %d\tK: %d\n", | |
| soil, temp, ec, ph, n, p, k); | |
| 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