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:
500Rounds to the nearest gram
printf("%d %d\n", scale_grams(4030, 4000, 40000), scale_grams(4019, 4000, 40000));Expected output:
1 0Learn it first
- Integers and data types · Fixed-width types, integer promotion, overflow and the signed/unsigned rules that bite.
More Integers and data types problems
- Add with carry · Add two bytes and report whether the result carried out of 8 bits.
- Unsigned difference · Return the distance between two unsigned values without wrapping.
- Sign-extend a 12-bit sample · Convert a 12-bit two's-complement reading into an int16_t.
- Saturate to a byte · Narrow a 32-bit value to uint8_t by clamping instead of wrapping.
- Signed against unsigned · Compare a signed value with an unsigned limit correctly.
- Average without overflow · Average two 32-bit values without a wider type.
- Divide and round to nearest · Integer division that rounds to the nearest value instead of truncating.
- Battery percentage · Map a battery voltage in millivolts to 0-100 percent.
- Checked signed addition · Add two int32_t values and report overflow without invoking undefined behaviour.
- Will the multiplication overflow? · Decide whether a 32-bit unsigned product fits in 32 bits.
- Fix: a crash on an empty sensor batch · The monitor faults when a batch has no samples.
- Fix: below zero, the freezer reads 255 °C · A 12-bit two's-complement reading is widened without its sign.
- Fix: checksums fail for some messages · Summing bytes through a plain char makes every byte above 0x7F count as negative.