diff options
author | Daniel Friesel <derf@finalrewind.org> | 2022-05-29 21:06:02 +0200 |
---|---|---|
committer | Daniel Friesel <derf@finalrewind.org> | 2022-05-29 21:06:02 +0200 |
commit | 6abca13a48be662b53ec98377a9e2edbb9aa8c9f (patch) | |
tree | 78415e6ce5ad8a2588f6b7403a0792687b4072be | |
parent | 5b2bbf44a723c4b27aa54ddcf8f138eaf7e4daea (diff) |
verify checksum
-rw-r--r-- | scd4x.lua | 28 |
1 files changed, 28 insertions, 0 deletions
@@ -36,10 +36,38 @@ function scd4x.read() end local data = i2c.read(scd4x.bus_id, 9) i2c.stop(scd4x.bus_id) + if not scd4x.crc_valid(data, 9) then + return nil + end local co2 = string.byte(data, 1) * 256 + string.byte(data, 2) local temp_raw = 175 * (string.byte(data, 4) * 256 + string.byte(data, 5)) local humi_raw = 100 * (string.byte(data, 7) * 256 + string.byte(data, 8)) return co2, temp_raw, humi_raw end +function scd4x.crc_word(data, index) + local crc = 0xff + for i = index, index+1 do + crc = bit.bxor(crc, string.byte(data, i)) + for j = 8, 1, -1 do + if bit.isset(crc, 7) then + crc = bit.bxor(bit.lshift(crc, 1), 0x31) + else + crc = bit.lshift(crc, 1) + end + crc = bit.band(crc, 0xff) + end + end + return bit.band(crc, 0xff) +end + +function scd4x.crc_valid(data, length) + for i = 1, length, 3 do + if scd4x.crc_word(data, i) ~= string.byte(data, i+2) then + return false + end + end + return true +end + return scd4x |