@@ -197,7 +197,7 @@ uint8_t NAU7802::getRevisionCode()
197197
198198// Returns 24-bit reading
199199// Assumes CR Cycle Ready bit (ADC conversion complete) has been checked to be 1
200- uint32_t NAU7802::getReading ()
200+ int32_t NAU7802::getReading ()
201201{
202202 _i2cPort->beginTransmission (_deviceAddress);
203203 _i2cPort->write (NAU7802_ADCO_B2);
@@ -208,9 +208,20 @@ uint32_t NAU7802::getReading()
208208
209209 if (_i2cPort->available ())
210210 {
211- uint32_t value = (uint32_t )_i2cPort->read () << 16 ; // MSB
212- value |= (uint32_t )_i2cPort->read () << 8 ; // MidSB
213- value |= (uint32_t )_i2cPort->read (); // LSB
211+ uint32_t valueRaw = (uint32_t )_i2cPort->read () << 16 ; // MSB
212+ valueRaw |= (uint32_t )_i2cPort->read () << 8 ; // MidSB
213+ valueRaw |= (uint32_t )_i2cPort->read (); // LSB
214+
215+ // the raw value coming from the ADC is a 24-bit number, so the sign bit now
216+ // resides on bit 23 (0 is LSB) of the uint32_t container. By shifting the
217+ // value to the left, I move the sign bit to the MSB of the uint32_t container.
218+ // By casting to a signed int32_t container I now have properly recovered
219+ // the sign of the original value
220+ int32_t valueShifted = (int32_t )(valueRaw << 8 );
221+
222+ // shift the number back right to recover its intended magnitude
223+ int32_t value = ( valueShifted >> 8 );
224+
214225 return (value);
215226 }
216227
@@ -219,9 +230,9 @@ uint32_t NAU7802::getReading()
219230
220231// Return the average of a given number of readings
221232// Gives up after 1000ms so don't call this function to average 8 samples setup at 1Hz output (requires 8s)
222- uint32_t NAU7802::getAverage (uint8_t averageAmount)
233+ int32_t NAU7802::getAverage (uint8_t averageAmount)
223234{
224- unsigned long total = 0 ;
235+ long total = 0 ;
225236 uint8_t samplesAquired = 0 ;
226237
227238 unsigned long startTime = millis ();
@@ -261,7 +272,7 @@ int32_t NAU7802::getZeroOffset()
261272// Call after zeroing. Provide the float weight sitting on scale. Units do not matter.
262273void NAU7802::calculateCalibrationFactor (float weightOnScale, uint8_t averageAmount)
263274{
264- uint32_t onScale = getAverage (8 );
275+ int32_t onScale = getAverage (averageAmount );
265276 float newCalFactor = (onScale - _zeroOffset) / (float )weightOnScale;
266277 setCalibrationFactor (newCalFactor);
267278}
@@ -281,7 +292,7 @@ float NAU7802::getCalibrationFactor()
281292// Returns the y of y = mx + b using the current weight on scale, the cal factor, and the offset.
282293float NAU7802::getWeight (bool allowNegativeWeights)
283294{
284- uint32_t onScale = getAverage (8 );
295+ int32_t onScale = getAverage (8 );
285296
286297 // Prevent the current reading from being less than zero offset
287298 // This happens when the scale is zero'd, unloaded, and the load cell reports a value slightly less than zero value
0 commit comments