Skip to content

Commit 2316b78

Browse files
author
Richard Unger
committed
Add CRC check to MT6835
1 parent 0255fcc commit 2316b78

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

src/encoders/mt6835/MT6835.cpp

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,39 @@ void MT6835::init(SPIClass* _spi) {
2626

2727

2828
float MT6835::getCurrentAngle(){
29-
return readRawAngle21() / (float)MT6835_CPR * _2PI;
29+
uint32_t rawangle = readRawAngle21();
30+
if (checkcrc) {
31+
if (lastcrc != calcCrc(rawangle, laststatus)) {
32+
laststatus |= MT6835_CRC_ERROR;
33+
return -1; // return -1 to signal CRC error - the current angle has to be non-negative otherwise
34+
}
35+
}
36+
return rawangle / (float)MT6835_CPR * _2PI;
37+
};
38+
39+
40+
// calculate crc8 of 21 angle bits and 3 status bits
41+
// polynomial: x^8 + x^2 + x + 1 = 0x07, (0xE0 reflected) init is 0x00, no final xor
42+
// TOOD table-based version
43+
uint8_t MT6835::calcCrc(uint32_t angle, uint8_t status) {
44+
uint8_t crc = 0x00;
45+
46+
uint8_t input = angle>>13;
47+
crc ^= input;
48+
for (int k = 8; k > 0; k--)
49+
crc = (crc & (0x01<<7))?(crc<<1)^0x07:crc<<1;
50+
51+
input = (angle>>5) & 0xFF;
52+
crc ^= input;
53+
for (int k = 8; k > 0; k--)
54+
crc = (crc & (0x01<<7))?(crc<<1)^0x07:crc<<1;
55+
56+
input = ((angle<<3) & 0xFF) | (status & 0x07);
57+
crc ^= input;
58+
for (int k = 8; k > 0; k--)
59+
crc = (crc & (0x01<<7))?(crc<<1)^0x07:crc<<1;
60+
61+
return crc;
3062
};
3163

3264

@@ -47,6 +79,7 @@ uint32_t MT6835::readRawAngle21(){
4779
digitalWrite(nCS, HIGH);
4880
spi->endTransaction();
4981
laststatus = data[4]&0x07;
82+
lastcrc = data[5];
5083
return (data[2] << 13) | (data[3] << 5) | (data[4] >> 3);
5184
};
5285

src/encoders/mt6835/MT6835.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#define MT6835_STATUS_OVERSPEED 0x01
2323
#define MT6835_STATUS_WEAKFIELD 0x02
2424
#define MT6835_STATUS_UNDERVOLT 0x04
25+
#define MT6835_CRC_ERROR 0x08
2526

2627
#define MT6835_WRITE_ACK 0x55
2728

@@ -202,14 +203,18 @@ class MT6835 {
202203
bool setZeroFromCurrentPosition();
203204
bool writeEEPROM(); // wait 6s after calling this method
204205

206+
bool checkcrc = false;
207+
205208
private:
206209
SPIClass* spi;
207210
SPISettings settings;
208211
int nCS = -1;
209212
uint8_t laststatus = 0;
213+
uint8_t lastcrc = 0;
210214

211215
void transfer24(MT6835Command* outValue);
212216
uint8_t readRegister(uint16_t reg);
213217
bool writeRegister(uint16_t reg, uint8_t value);
218+
uint8_t calcCrc(uint32_t angle, uint8_t status);
214219

215220
};

0 commit comments

Comments
 (0)