SE050 Driver
API reference
Loading...
Searching...
No Matches
se050_crc.hpp
Go to the documentation of this file.
1
13#pragma once
14
15#include <cstddef>
16#include <cstdint>
17
18namespace se050::crc {
19
27[[nodiscard]] inline std::uint16_t Crc16Edc7816(const std::uint8_t* buffer, std::size_t offset,
28 std::size_t length) noexcept {
29 std::uint16_t crc = 0xFFFFU;
30 for (std::size_t i = offset; i < offset + length; ++i) {
31 crc ^= static_cast<std::uint16_t>(buffer[i]);
32 for (int bit = 8; bit > 0; --bit) {
33 if ((crc & 0x0001U) != 0U) {
34 crc = static_cast<std::uint16_t>((crc >> 1) ^ 0x8408U);
35 } else {
36 crc = static_cast<std::uint16_t>(crc >> 1);
37 }
38 }
39 }
40 crc = static_cast<std::uint16_t>(crc ^ 0xFFFFU);
41 return crc;
42}
43
45inline void AppendEdc(std::uint8_t* frame, std::size_t len_without_edc) noexcept {
46 const std::uint16_t c = Crc16Edc7816(frame, 0, len_without_edc);
47 frame[len_without_edc] = static_cast<std::uint8_t>(c & 0xFFU);
48 frame[len_without_edc + 1U] = static_cast<std::uint8_t>((c >> 8) & 0xFFU);
49}
50
52[[nodiscard]] inline bool VerifyFrameCrc(const std::uint8_t* frame, std::size_t total_len) noexcept {
53 if (total_len < 5U) {
54 return false;
55 }
56 const std::uint16_t recv =
57 static_cast<std::uint16_t>(static_cast<std::uint16_t>(frame[total_len - 1U]) << 8 |
58 frame[total_len - 2U]);
59 const std::uint16_t calc = Crc16Edc7816(frame, 0, total_len - 2U);
60 return recv == calc;
61}
62
63} // namespace se050::crc
Definition se050_crc.hpp:18
bool VerifyFrameCrc(const std::uint8_t *frame, std::size_t total_len) noexcept
Verify EDC on a full received frame (includes trailing 2-byte CRC).
Definition se050_crc.hpp:52
void AppendEdc(std::uint8_t *frame, std::size_t len_without_edc) noexcept
Append EDC immediately after frame[0 .. len_without_edc-1].
Definition se050_crc.hpp:45
std::uint16_t Crc16Edc7816(const std::uint8_t *buffer, std::size_t offset, std::size_t length) noexcept
Compute T=1 EDC over bytes [offset, offset+length) of buffer.
Definition se050_crc.hpp:27