SparkFun Forums 

Where electronics enthusiasts find answers.

Have questions about a SparkFun product or board? This is the place to be.
By sspence65
#184911
What is the proper syntax for saving the scale output in a variable?

float value;

Serial.print(scale.getGram(), 1); <—– WORKS

value = (scale.getGram(), 1) ;

Serial.println(value); <—– NO GOOD! DISPLAYS: “1.00”

value = (scale.getGram(), 2) ;

Serial.println(value); <—– NO GOOD! DISPLAYS: “2.00”
User avatar
By DanV
#184919
I can't tell what you're programming platform is (or even what control you're using) but, is the syntax for the assignment
:=
and not just
=
??
By sspence65
#184921
The use of the comma token as an operator is distinct from its use in function calls and definitions, variable declarations, enum declarations, and similar constructs, where it acts as a separator.

This is being used as a separator in a function, to notify the function how many decimal points to return. In this case one, so it returns 10.5 grams as a float.

In arduino C/C++, = is used as an assignment, but it's assigning 10.0, not 10.5 to the variable.
By jremington
#184924
In arduino C/C++, = is used as an assignment, but it's assigning 10.0, not 10.5 to the variable.

The "but" and the "10.0" in this statement suggests that you haven't yet figured it out, so here is a little program to try:
Code: Select all
void setup() {
  Serial.begin(9600);
}

// pretend to be a sensor
float sensor(void) {return 12.3;}

void loop() {

  float sensorValue = (sensor(), 1);
  Serial.println(sensorValue);

  sensorValue = sensor();
  Serial.println(sensorValue);

  delay(1000);
}
By sspence65
#184925
In your example:

float sensorValue = (sensor(), 1);
Serial.print(sensorValue);
outputs 1.00

and

sensorValue = sensor();
Serial.println(sensorValue);
outputs 12.30

but your routine is not accepting ,1 as a designation how many decimal places sensor() is supposed to return. The library for the HX711 takes that input and passes back 12.3, or 12.35 as a result.

I know this because if I pass ,1 I get 12.3, and If I pass ,2, I get 12.35. The library documentation describes this.
By jremington
#184926
You are still confused.
The following line calls scale.getGram with NO parameters, the value returned by scale.getGram() is discarded and the comma operator returns a 1, which is finally stored in value.
Code: Select all
value = (scale.getGram(), 1) ;
By sspence65
#184928
Ok, I'm getting it now. that ,1 or ,2 is a instruction to Serial.print how many decimals to print. I need to drop that off, and use

value = scale.getGram();
Serial.println(value);
By jremington
#184929
In the following line the ",1" is a parameter to Serial.print(), which specifies how many decimal places to print.
Code: Select all
Serial.print(scale.getGram(), 1);
The ",1" does nothing to the value itself.