/** Receives a packet from the SL018. * * @param length the number of bytes to receive * @return the number of bytes in the payload, or -1 if bad checksum */ byte SL018::receiveData(byte length) { // wait until at least 20ms passed since last I2C transmission while(t > millis()); t = millis() + 20; // read response Wire.requestFrom(address, length); if(Wire.available()) { // get length of packet data[0] = Wire.receive(); // get data for (byte i = 1; i <= data[0]; i++) { data[i] = Wire.receive(); } // show received packet for debugging if (debug && data[0] > 0 ) { Serial.print("< "); printArrayHex(data, data[0] + 1); Serial.println(); } // return with length of response return data[0]; } return 0; }
/** Transmit a packet to the SL018. */ void SL018::transmitData() { // wait until at least 20ms passed since last I2C transmission while(t > millis()); t = millis() + 20; // remember which command was sent cmd = data[1]; // transmit packet with checksum Wire.beginTransmission(address); for (int i = 0; i <= data[0]; i++) { Wire.send(data[i]); } Wire.endTransmission(); // show transmitted packet for debugging if (debug) { Serial.print("> "); printArrayHex(data, data[0] + 1); Serial.println(); } }
/** Receives a packet from the SM130 and verifies the checksum. * * @param length the number of bytes to receive * @return the number of bytes in the payload, or -1 if bad checksum */ byte SM130::receiveData(byte length) { // wait until at least 20ms passed since last I2C transmission while(t > millis()); t = millis() + 20; // read response Wire.requestFrom(address, length); byte n = Wire.available(); // get data if available if(n > 0) { for (byte i = 0; i < n;) { #if defined(ARDUINO) && ARDUINO >= 100 data[i++] = Wire.read(); #else data[i++] = Wire.receive(); #endif } // show received packet for debugging if (debug && data[0] > 0 ) { Serial.print("< "); printArrayHex(data, n); Serial.println(); } // verify checksum if length > 0 and <= SIZE_PAYLOAD if (data[0] > 0 && data[0] <= SIZE_PAYLOAD) { byte i, sum; for (i = 0, sum = 0; i <= data[0]; i++) { sum += data[i]; } // return with length of response, or -1 if invalid checksum return sum == data[i] ? data[0] : -1; } } return 0; }
/** Transmit a packet with checksum to the SM130. */ void SM130::transmitData() { // wait until at least 20ms passed since last I2C transmission while(t > millis()); t = millis() + 20; // init checksum and packet length byte sum = 0; byte len = data[0] + 1; // remember which command was sent cmd = data[1]; // transmit packet with checksum //Wire.beginTransmission(address); for (int i = 0; i < len; i++) { #if defined(ARDUINO) && ARDUINO >= 100 Wire.write(data[i]); #else Wire.send(data[i]); #endif sum += data[i]; } #if defined(ARDUINO) && ARDUINO >= 100 Wire.write(sum); #else Wire.send(sum); #endif Wire.endTransmission(); // show transmitted packet for debugging if (debug) { Serial.print("> "); printArrayHex(data, len); Serial.print(' '); printHex(sum); Serial.println(); } }