| 300 | |
| 301 | |
| 302 | int AM232X::_getData(uint8_t length) |
| 303 | { |
| 304 | int bytes = _wire->requestFrom(AM232X_ADDRESS, length); |
| 305 | if (bytes == 0) return AM232X_ERROR_CONNECT; |
| 306 | |
| 307 | for (int i = 0; i < bytes; i++) |
| 308 | { |
| 309 | _bits[i] = _wire->read(); |
| 310 | } |
| 311 | |
| 312 | // ANALYZE ERRORS |
| 313 | // will not detect if we requested 1 byte as that will |
| 314 | // return 5 bytes as requested. E.g. getStatus() |
| 315 | // design a fix if it becomes a problem. |
| 316 | if (bytes != length) |
| 317 | { |
| 318 | switch (_bits[3]) |
| 319 | { |
| 320 | case 0x80: return AM232X_ERROR_FUNCTION; |
| 321 | case 0x81: return AM232X_ERROR_ADDRESS; |
| 322 | case 0x82: return AM232X_ERROR_REGISTER; |
| 323 | case 0x83: return AM232X_ERROR_CRC_1; // previous write had a wrong CRC |
| 324 | case 0x84: return AM232X_ERROR_WRITE_DISABLED; |
| 325 | default: return AM232X_ERROR_UNKNOWN; |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | // CRC is LOW Byte first |
| 330 | uint16_t crc = _bits[bytes - 1] * 256 + _bits[bytes - 2]; |
| 331 | if (_crc16(&_bits[0], bytes - 2) != crc) |
| 332 | { |
| 333 | return AM232X_ERROR_CRC_2; // read itself has wrong CRC |
| 334 | } |
| 335 | |
| 336 | return AM232X_OK; |
| 337 | } |
| 338 | |
| 339 | |
| 340 | uint16_t AM232X::_crc16(uint8_t *ptr, uint8_t len) |