Skip to content

Commit

Permalink
Fix CRC calculation for TX frames
Browse files Browse the repository at this point in the history
* Add number of command bytes, since they must not be included
  when deciding if a CRC should be included
* CRC is added every third byte excluding command bytes
  • Loading branch information
psachs committed Aug 3, 2021
1 parent 78e9091 commit 4b2d402
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
10 changes: 6 additions & 4 deletions src/SensirionI2CTxFrame.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@
#include "SensirionErrors.h"

SensirionI2CTxFrame::SensirionI2CTxFrame(uint8_t buffer[], size_t bufferSize,
size_t index)
: _buffer(buffer), _bufferSize(bufferSize), _index(index) {
size_t numCommandBytes)
: _buffer(buffer), _bufferSize(bufferSize), _index(numCommandBytes),
_numCommandBytes(numCommandBytes) {
}

SensirionI2CTxFrame::SensirionI2CTxFrame(uint8_t buffer[], size_t bufferSize)
Expand All @@ -57,7 +58,8 @@ SensirionI2CTxFrame
SensirionI2CTxFrame::createWithUInt16Command(uint16_t command, uint8_t buffer[],
size_t bufferSize) {
SensirionI2CTxFrame instance = SensirionI2CTxFrame(buffer, bufferSize, 2);
instance.addCommand(command);
instance._buffer[0] = static_cast<uint8_t>((command & 0xFF00) >> 8);
instance._buffer[1] = static_cast<uint8_t>((command & 0x00FF) >> 0);
return instance;
}

Expand Down Expand Up @@ -144,7 +146,7 @@ uint16_t SensirionI2CTxFrame::_addByte(uint8_t data) {
return TxFrameError | BufferSizeError;
}
_buffer[_index++] = data;
if (_index % 2 == 0) {
if ((_index - _numCommandBytes) % 3 == 2) {
if (_bufferSize <= _index) {
return TxFrameError | BufferSizeError;
}
Expand Down
4 changes: 3 additions & 1 deletion src/SensirionI2CTxFrame.h
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,8 @@ class SensirionI2CTxFrame {
uint16_t addBytes(const uint8_t data[], size_t dataLength);

private:
SensirionI2CTxFrame(uint8_t buffer[], size_t bufferSize, size_t index);
SensirionI2CTxFrame(uint8_t buffer[], size_t bufferSize,
size_t numCommandBytes);

static uint8_t _generateCRC(const uint8_t* data, size_t count);

Expand All @@ -184,6 +185,7 @@ class SensirionI2CTxFrame {
uint8_t* _buffer;
size_t _bufferSize;
size_t _index;
size_t _numCommandBytes;
};

#endif /* SENSIRION_I2C_TX_FRAME_H_ */

0 comments on commit 4b2d402

Please sign in to comment.