From dd7e55d7a6c7d2ae82fef2e3dcf063101f3c850e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Krac=C3=ADk?= Date: Wed, 12 Jun 2019 01:04:16 +0200 Subject: [PATCH] BCC Checksum calculation --- ZPA_elektromer_UARTtest.ino | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/ZPA_elektromer_UARTtest.ino b/ZPA_elektromer_UARTtest.ino index 7fc083d..f4fc101 100644 --- a/ZPA_elektromer_UARTtest.ino +++ b/ZPA_elektromer_UARTtest.ino @@ -78,8 +78,17 @@ void setup() { } +// BCC is calculated as follows (source https://github.com/lvzon/dsmr-p1-parser/blob/master/doc/IEC-62056-21-notes.md): +// The BCC is calculated over the bytes after STX up to and including the ETX byte +// To calculate this BCC, take the first byte XOR 0xff +// XOR this value with the second byte, and so forth up to and including the last byte (include 0x03 ETX !!), +// and XOR the final value with 0xff. + +bool firstBCCbyte = false; +uint8_t localBCC = 0; + void loop() { - // put your main code here, to run repeatedly: + ArduinoOTA.handle(); @@ -88,19 +97,34 @@ void loop() { if (r == 0x02) { Serial.print(""); + firstBCCbyte = true; + uint8_t localBCC = 0; return; } if (r == 0x03) { Serial.println(""); Serial.print("Checksum : "); - Serial.println(Serial2.read()); + Serial.print(Serial2.read()); + Serial.println(); + Serial.print("Calculated : "); + localBCC = localBCC ^ 0x03; + localBCC = localBCC ^ 0xFF; + Serial.print(localBCC); + Serial.println(); Serial.println(); Serial.println("Changing back baudrate to 300"); Serial2.updateBaudRate(300); return; } + // Calculate BCC checksum + if (firstBCCbyte) { + firstBCCbyte = false; + localBCC = r ^ 0xFF; + } else { + localBCC = localBCC ^ r; + } Serial.write(r); }