From da68ff5ad6ac3dbe187386b10c311b50be46dd10 Mon Sep 17 00:00:00 2001 From: rusefillc Date: Mon, 22 Nov 2021 14:03:52 -0500 Subject: [PATCH] j1850 SAE crc8 --- firmware/util/math/crc.c | 21 +++++++++++++++++++++ firmware/util/math/crc.h | 1 + unit_tests/tests/test_util.cpp | 6 ++++++ 3 files changed, 28 insertions(+) diff --git a/firmware/util/math/crc.c b/firmware/util/math/crc.c index 8236034ff8..c4c1e16f79 100644 --- a/firmware/util/math/crc.c +++ b/firmware/util/math/crc.c @@ -95,6 +95,27 @@ uint32_t crc32(const void *buf, uint32_t size) { return crc32inc(buf, 0, size); } +/** + * http://www.sunshine2k.de/coding/javascript/crc/crc_js.html + * https://stackoverflow.com/questions/38639423/understanding-results-of-crc8-sae-j1850-normal-vs-zero + * j1850 SAE crc8 + */ +uint8_t crc8(const uint8_t *data, uint8_t len) { + uint8_t crc = 0; + + if (data == 0) + return 0; + crc ^= 0xff; + while (len--) { + crc ^= *data++; + for (unsigned k = 0; k < 8; k++) + crc = crc & 0x80 ? (crc << 1) ^ 0x1d : crc << 1; + } + crc &= 0xff; + crc ^= 0xff; + return crc; +} + uint32_t crc32inc(const void *buf, uint32_t crc, uint32_t size) { const uint8_t *p; diff --git a/firmware/util/math/crc.h b/firmware/util/math/crc.h index 7e8d647548..83d897c270 100644 --- a/firmware/util/math/crc.h +++ b/firmware/util/math/crc.h @@ -16,6 +16,7 @@ extern "C" { #endif /* __cplusplus */ crc_t calc_crc(const crc_t message[], int nBytes); +uint8_t crc8(const uint8_t * buf, uint8_t len); uint32_t crc32(const void *buf, uint32_t size); uint32_t crc32inc(const void *buf, uint32_t crc, uint32_t size); diff --git a/unit_tests/tests/test_util.cpp b/unit_tests/tests/test_util.cpp index f391895988..a0995a0ab2 100644 --- a/unit_tests/tests/test_util.cpp +++ b/unit_tests/tests/test_util.cpp @@ -29,6 +29,12 @@ TEST(util, negativeZero) { ASSERT_FALSE(IS_NEGATIVE_ZERO(0.0)); } +TEST(util, crc8) { + const uint8_t crc8_tab[] = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38}; + + ASSERT_EQ(0xB, crc8(crc8_tab, 8)); +} + TEST(util, crc) { ASSERT_EQ(4, efiRound(4.4, 1)); ASSERT_FLOAT_EQ(1.2, efiRound(1.2345, 0.1));