Sharing Values in Source Files

Within a library, it is quite common to have one function depend upon information provided by another function. The other function can be inside the same source file, in a different source file in the same library, or even in a different library.  Oftentimes, functions can share information directly through parameter arguments and return values, without the need for anything more than local variables. Sometimes, variables that are global to the source file or to a library are necessary. 


Sharing Values with Local Variables

Below is an example from the simple library source file ping.c, showing two of its functions.  If your project has a PING))) Ultransonic Distance Sensor connected to an I/O pin,  you can call ping_cm to get a distance measurement reading from the sensor in centimeters. 

Lets's see how local variables, parameters and return values pass information around inside the ping.c library to get that distance measurement. Imagine your application code makes a function call:  int dist = ping_cm(8);

  1. Your application code calls the ping_cm function, passing 8 to its pin parameter.
  2. The ping_cm function starts by calling the ping function inside the same source file, passing along the value 8 to its pin parameter. 
  3. The ping function receives the value 8 in its own pin parameter, to pass to other function calls in its own code block.
  4. The ping function calls three other functions from the simpletools library, and passes each one the value 8 for their pin parameters: low, pulse_out, and pulse_in.  The last line in this code block, return pulse_in(pin, 1); uses the return value from the pulse_in call as the return value for the entire ping function call.
  5. The ping function's return value is sent back to where it was called, and is stored in the local long variable tEcho.  On the next line, tEcho is divided by 58, and the result is stored in the local int variable cmDist.
  6. Last, cmDist is used as the return value for the ping_cm function, so whatever value it holds returns to the ping_cm function call in the application code. Here, it is stored in the local int variable dist.  Now your application code can use dist to take action based on the distance measured by the sensor.


When to Use Global Variables

If your library launches a function into another cog with cogstart or cog_run, your code may need to use global variables to exchange information.  In the next activity, we'll modify the awesome library so that multiple functions in the same file share a variable.  In the activity after that we’ll look at how functions in multiple files can share variables.