Created
June 15, 2024 11:56
-
-
Save maxpromer/8fc1b7f2e6a24c46ef60d7a6eec6a7b2 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 (27) | |
#define RS485_TX_PIN (26) | |
ModbusMaster sensor; | |
void setup() { | |
Serial.begin(115200); | |
// Modbus communication runs at 9600 baud | |
Serial2.begin(9600, SERIAL_8N1, RS485_RX_PIN, RS485_TX_PIN); // AdapBit | |
// Sensor init with Modbus slave ID 1 | |
sensor.begin(1, Serial2); | |
} | |
void loop() { | |
// Read | |
uint8_t result; | |
result = sensor.readHoldingRegisters(0, 7); // Read Input Register start at 0 -> 7 word (0x0000 - 0x0006) | |
if (result == sensor.ku8MBSuccess) { | |
int unit = sensor.getResponseBuffer(2); | |
int decimal = sensor.getResponseBuffer(3); | |
float value = sensor.getResponseBuffer(4); | |
value /= pow(10, decimal); | |
Serial.print("Level: "); | |
Serial.print(value); | |
if (unit == 1) { | |
Serial.print(" CM"); | |
} else if (unit == 2) { | |
Serial.print(" MM"); | |
} else if (unit == 3) { | |
Serial.print(" MPa"); | |
} else if (unit == 4) { | |
Serial.print(" Pa"); | |
} else if (unit == 5) { | |
Serial.print(" KPa"); | |
} else if (unit == 6) { | |
Serial.print(" MA"); | |
} | |
Serial.println(); | |
delay(1000); | |
} else { | |
Serial.println("Read sensor 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