Simvik

Kitchen scale: grams from a load cell

Turn a raw load-cell count into grams, with the tare taken off and the result rounded. An easy embedded C problem (Integers and data types), run and graded…

easy · Integers and data types · integers · rounding · overflow · product

Product: Kitchen scale (Consumer electronics)

Requirement. The scale shows the weight in whole grams, rounded to the nearest gram, and an empty bowl reads 0.

The load cell's converter gives a raw count. tare is the count with nothing on the scale (taken when the user presses Tare), and counts_per_kg comes from the factory calibration. Return the net weight in grams, rounded to the nearest gram (halves away from zero). It can be negative, when the user lifts the bowl after taring.

Raw counts go up to 8,000,000.

Starter code

int32_t scale_grams(int32_t raw, int32_t tare, int32_t counts_per_kg) {
  return (raw - tare) / counts_per_kg * 1000;
}

Example tests

A 500 g weight

printf("%d\n", scale_grams(25000, 5000, 40000));

Expected output:

500

Rounds to the nearest gram

printf("%d %d\n", scale_grams(4030, 4000, 40000), scale_grams(4019, 4000, 40000));

Expected output:

1 0

Learn it first

More Integers and data types problems