Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ModbusMaster.h>
- ModbusMaster node;
- // Struktur Union untuk konversi Float (32-bit)
- union FloatConverter {
- uint16_t regs[2];
- float value;
- };
- // Struktur Union untuk konversi Unsigned Long / uint32_t (32-bit)
- union UlongConverter {
- uint16_t regs[2];
- uint32_t value;
- };
- void setup() {
- Serial.begin(115200);
- // node.begin(1, Serial2); // Sesuaikan ID Slave dan Serial Modbus Anda
- }
- void loop() {
- // Ambil data setiap 5 detik
- bacaPrimaryActiveEnergy();
- bacaSecondaryActiveEnergy();
- Serial.println("--------------------------------------------");
- delay(5000);
- }
- // ====================================================================
- // CONTOH 1: Membaca Sisi PRIMARY SIDE (Tipe Data: Float)
- // ====================================================================
- void bacaPrimaryActiveEnergy() {
- // Alamat 0x008A (Total positive active energy - Primary)
- uint8_t result = node.readHoldingRegisters(0x008A, 2);
- if (result == node.ku8MBSuccess) {
- FloatConverter dataPrimary;
- // Sesuaikan urutan word (Big-Endian format)
- dataPrimary.regs[1] = node.getResponseBuffer(0); // High Word
- dataPrimary.regs[0] = node.getResponseBuffer(1); // Low Word
- float kwh_primary = dataPrimary.value;
- Serial.print("[PRIMARY] Total Positive Active Energy: ");
- Serial.print(kwh_primary, 2);
- Serial.println(" kWh (Nilai aktual lapangan)");
- } else {
- Serial.printf("[PRIMARY] Gagal membaca register! Error: 0x%02X\n", result);
- }
- }
- // ====================================================================
- // CONTOH 2: Membaca Sisi SECONDARY SIDE (Tipe Data: Ulong)
- // ====================================================================
- void bacaSecondaryActiveEnergy() {
- // Alamat 0x0082 (Total positive active energy - Secondary)
- uint8_t result = node.readHoldingRegisters(0x0082, 2);
- if (result == node.ku8MBSuccess) {
- UlongConverter dataSecondary;
- // Gabungkan bitwise atau menggunakan union
- dataSecondary.regs[1] = node.getResponseBuffer(0); // High Word
- dataSecondary.regs[0] = node.getResponseBuffer(1); // Low Word
- uint32_t raw_value = dataSecondary.value;
- // Sesuai keterangan di datasheet: dikali faktor skala 0.001
- float kwh_secondary = (float)raw_value * 0.001;
- Serial.print("[SECONDARY] Raw Value: ");
- Serial.print(raw_value);
- Serial.print(" | Terkonversi: ");
- Serial.print(kwh_secondary, 3);
- Serial.println(" kWh (Sisi Sekunder Sensor)");
- } else {
- Serial.printf("[SECONDARY] Gagal membaca register! Error: 0x%02X\n", result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment