Home > OS >  my function-definition seems not get included in void loop
my function-definition seems not get included in void loop

Time:01-06

I was practicing and trying my Analog to Digital Converter and trying this simple test. And here is my code :

#include <Adafruit_MCP3008.h>

Adafruit_MCP3008 adc;

  float voltage(int raw){
  return raw / 1023 * 4.9;
}

void setup() {
  Serial.begin(9600);
  while (!Serial);
  Serial.println("MCP3008 simple test.");

  adc.begin();
  
}

void loop() {
  int raw = adc.readADC(0);

  Serial.print(raw);
  Serial.print("\t");
  Serial.println(voltage(raw));

  delay(1000);
}

and when I opened my serial monitor it only showing the changes of "raw", but my "voltage" function seems not get included, here is what I got, as you can see it only shows the result for raw (on left), but not showing the voltage (on right) serial monitor

I'm trying to make sure I got the "voltage" function affected also inside the void loop. can anybody explain me the rule of program in this case ?

CodePudding user response:

Integer division

raw / 1023 results in 0, 1, .... Not a fraction.

Use float math instead of double

For a float task, use float constants. This avoids a lot of unneeded widening and narrowing of floating point code.

float voltage(int raw){
  // double divide, double *, convert to float
  // return raw / 1023.0 * 4.9;

  // float divide, float *
  return raw / 1023.0f * 4.9f;
}

Help the compiler

Strict code complilation cannot combine the / and *, incurring 2 operations including a heavy /. FP math is not associative. Yet we can in source code.

Also avoid naked magic numbers.

#define ADC_V_MAX 4.9f
#define ADC_N_MAX 1023 
float voltage(int raw){
  return raw * (ADC_V_MAX / ADC_N_MAX);
}

Sure about range?

I'd expect:

#define ADC_V_MAX 5.0f
#define ADC_N_MAX 1024 

A 10-bit A/D converter typically maps 1024 to the top voltage 5.0, even though only 0-1023 is produced.

CodePudding user response:

I think you have a conversion problem. You are passing a int and divide it by 1023. This would give you 0, then multiplied by 4.9 would give you 0.0

You should cast your int raw into a float.

CodePudding user response:

turn out it was not the function definition, it was mathematical order, silly me :sweat_smile:

this fixed my issue :

float voltage(int raw)
{
return (raw * 4.9) / 1023 ;
}
  • Related