Programming difficulty about function definition

I was practicing and trying my Analog to Digital Converter (MCP3008) 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)
Screenshot (62)

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 ?

Try this

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

return raw / 1024.0 * 4.9;

Hi,
Do the maths.

119/1023 = 0.116 so as an integer the result is 0.
so 0 * 4.9 = 0

You need to look at using float rather than int variables.

Tom.. :smiley: :+1: :coffee: :australia:
PS. Do the multiplication before the division.

So with an int as parameter

float voltage(int raw){
  // it is important to have the "1.0" DOT-ZERO
  // to make the compiler handle it explicit as float
  float myFLoat = raw * 1.0; 
  myFLoat = myFLoat / 1023 * 4.9;
  return myFLoat;
}

or simply

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


OMG thanks for the clear info, so the problem was the mathematical order damn....
I tried this and it solved

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

thank you for noticing the problem guys

Or, correctly, divide by 1024.
It's a small thing, but small things can be important (unlike Andrew Tate's you-know-what)

yup yup silly me, now my problem fixed by doing this :

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

thank you

yup thank you for noticing first, I did this instead :

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

and it fixed my program issue, turn out it was not the function definition, it was mathematical order, silly me :sweat_smile:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.