Using "Void"

First a quick thank you to all for helping me devote many happy hours to aggravating my myopia!

Presently, I only write sketches with void setup and void loop

but i see many sketches with other void functions. The reference page says:

The void keyword is used only in function declarations. It indicates that the function is expected to return no information to the function from which it was called.

I can't get my head around this. would somebody please tell me how to better use void to make my sketches work better. No information to the function...hmmmm.

For example I am experimenting with I2C networking. I have a master and slave Uno flashed with the sketches from an old posting ca. 2010: http://forum.arduino.cc/index.php?topic=48477.0 and it works.

Here is a part of the code from the Slave sender after the void loop closing brace:

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestInt()
{
if (byteSending == 1) //send packet 1
{
toSend = Shift & mask;
..........and so on

I need to understand that using "void requestInt()" is better or needed...why cant it just live in the void loop? I know I am missing something big picture here.

I see that Up in set up there is this line

Wire.onRequest(requestInt); // register event

What is the significant of registering this event?

.. I think this is how the master/slave coordinate their coms but I'm stuck on what significantly effects when a void function is called. I'd better leave it that.

I have several years experience writing sketches that turn things on and off, PWM control of our sunroom vent and various outputs using feedback from temperature, pressure ...analog sensors. My biggest weakness (perhaps obviously) is thinking logically like a computer. Too much Guiness maybe?

cheers

It’s hard to get a question out of this. Can you be more specific?

"We tried to talk it over, but the words got in the way..."

When is it appropriate to use "void XXXX" when thinking about a sketch design?

If your question is what does a "void" function do, then I can give you an example.

If I had a void returned function that does something in 100 lines, and if I needed to call it 10 times differently, then I refuse to copy/paste that 100 lines 10 times...
For example, Serial.print(); is not a void function, but it very well could be...just pretend it is...
If I did something like...

Serial.print("========");
Serial.print("Derp Derp Derp");
Serial.print("========");

Then I would have to copy/paste everything that that function does 3 times...which is pointless and a waste of code and space.

A void function simply means that it runs some code (like any other function), then when it is done, leaves the function and goes back to where it was called (like any other function). It does not return anything. If you tried to do something like...

int x = someVoidFunction();

It would give you an error because it doesn't return anything, it is basically like writing...

int x = ;

I need to understand that using "void requestInt()" is better or needed...why cant it just live in the void loop? I know I am missing something big picture here.

You could, but this is much more tedious and wasteful...or you could use the keywork "inline". The inline keyword basically does that for you at compile time. It is useful for small functions that you want to run as fast as possible and want no overhead from calling/returning from a function. Check it out.
http://www.cplusplus.com/articles/2LywvCM9/

Ps991

A void function simply means that it runs some code (like any other function), then when it is done, leaves the function and goes back to where it was called (like any other function). It does not return anything. If you tried to do something like...

Thats what I was looking for. I know what to do now. I can try it out. good one.

will check that url too

much obliged

Procyan:
I need to understand that using "void requestInt()" is better or needed...why cant it just live in the void loop? I know I am missing something big picture here.

I think you're confusing 'void' with 'function'.

Functions have two purposes. The most used one is re-usability of some of code. Imagine that you want toggle the onboard LED under a given condition.

// if button pressed
if(digitalRead(toggleButton) == LOW)
{
  // if LED off
  if(digitalRead(ledPin) == LOW)
  {
    // switch LED on
    digitalWrite(ledPin, HIGH);
  }
  else
  {
    // if LED on
    digitalWrite(ledPin, LOW);
  }
}

If you want to do that at 100 different places your code grows out of hand. So you place the actual toggling in a function (e.g. toggleLed()) and call that function. You save about 10 lines each time that you need to toggle the LED.

void loop()
{
  // if button pressed
  if(digitalRead(toggleButton) == LOW)
  {
    // toggle ledPin
    toggleLed(ledPin);
  }
}

void toggleLed(int pin)
{
  // if LED off
  if(digitalRead(pin) == LOW)
  {
    // switch LED on
    digitalWrite(pin, HIGH);
  }
  else
  {
    // if LED on
    digitalWrite(pin, LOW);
  }
}

The above toggleLed() function also allows you to pass a pin as an argument, so you can use it for different pins that have LEDs connected to them by passing a different pin number.

The second purpose is pure readability. Imagine that you do a calculation in loop() and that calculation is 100 lines long. You will easily loose the overview while editing your code; you have to scroll 100 lines to get to the next point in your code. So you place that in a function and call that function. It keeps your code readable.

Regarding 'void'. 'void' simply indicates that the function does not return a value. It usually depends on the compiler how forgiving it is but it can throw a warning (not tested) if you e.g. try to return an integer from a function that is declared as void.

Procyan:
The reference page says:

The void keyword is used only in function declarations. It indicates that the function is expected to return no information to the function from which it was called.

The reference is incomplete as you can pass void arguments to a function as well. This is some more advanced stuff though and its usefulness might not be clear now. But added for completeness.

void setup()
{
  // put your setup code here, to run once:

}

void loop()
{
  int theNumberAsInteger;
  // character array to store ascii representation of number
  char number[] = "1234";
  // do something with number
  theNumberAsInteger = myfunc(number);

  
}

// a function that takes a pointer to a void and returns an int
int myfunc(void *ptr)
{
  // print the receivfed character array
  Serial.println((char*)ptr);
  // convert to integer
  int value = atoi((char*)ptr);
  // print the value
  Serial.println(value);
  // return the value
  return value;
}

sterretje, again i say thank you...you have just described my problem...as my projects get more sophisticated i find the code becoming long an cumbersome. This is a real breakthrough for me.

in your first example am i correct that the loop runs over and over as usual but then when it detects the button pin going LOW it steps out to void toggleLed? then back to loop until the condition is met again with another button push...of course

Brilliant...I could have used this many times in the past. hahaha. I can't wait to try this out on a sketch i'm working on now.

Tell me, do most noobs figure this out on their own? I had a vague feeling that it had to do with the flow of execution but just couldnt get it aligned in my gob.

let me get something working before i get too excited. but i do think I understand now.

1 Like

Depends on if you have prior programming experience (BASIC doesn't count, seriously). If you do, it's what you'd expect, and makes sense. If not, no, it doesn't really make sense without some background. Not sure how many people whose first programming is arduino "get it" without a bit of a struggle.

BASIC doesn't count, seriously

That depends on the version of BASIC being used.

Procyan:
in your first example am i correct that the loop runs over and over as usual but then when it detects the button pin going LOW it steps out to void toggleLed? then back to loop until the condition is met again with another button push...of course

That is how it works.

Procyan:
Tell me, do most noobs figure this out on their own? I had a vague feeling that it had to do with the flow of execution but just couldnt get it aligned in my gob.

I honestly can't remember. During my study (electronics), we did a little Pascal and assembly. Functions were covered but not the specific case that they can make code more easy to read; I think that I somewhere had some light bulb moment when my code grew out of control and created a function for something that only was done once. That knowledge however might have come from a book as well.

Referring chapter 1.7 in the old bible (Kernighan and Ritchie, the C programming language)

you will often see a short function defined and called only once, just because it clarifies some piece of code.

OK, I mentioned a 100 lines of code (not really short) but the above gives another idea as to why you might want to add / use a function.

Like other I can't remember when I learnt about functions. It just sort of happened. Although it is not immediately obvious, you use functions from the first time you use an Arduino. The built in functions such as pinMode() provide much functionality in the Arduino environment and where would you be without setup() and loop() ?

Functions are useful when code needs to be repeated several times in a program, particularly when you can pass parameters. They are also useful because you can give them meaningful names that indicate what they do. Splitting code into functions, even if the function is only called once, makes it easier to make changes to a block of code, add debugging output and reuse the function in another program if it is useful. To a certain extent you can even write dummy functions that do nothing apart from printing a message indicating that they have been called so that you can test program flow.

The main confusion seems to be that many (most ?) functions do not return a value and are, therefore, declared void. This leads to functions being referred to as voids which is not a very helpful search term.

The main confusion seems to be that many (most ?) functions do not return a value and are, therefore, declared void. This leads to functions being referred to as voids which is not a very helpful search term.

The interesting twist to that is that if you learn C programming first, main() has a return type. So, the tendency for new programmers is to think that every function needs to return an int, and it can be challenging to teach that a function doesn't have to return a value. In beginner C classes, students never refer to functions as voids.

It wasn't until C++ came along that void as a return type became so common.