programming

Functions with variable lenght arguments in Arduino

Submitted by fabio on Wed, 2012-01-18 17:27.

I was reading about variable length arguments for functions in the C programming language and I thought, "hey, will this thing work on an Arduino?".. well, it turns out that yes, it's working great!

But, what are functions with a variable length? Well, the standard C printf function is a good example (not available on Arduino of course). You can call it with how many arguments you want, for example:

printf("%d", 5);
printf("%d %d", 5, 7);

So, how can we make this with the Arduino? Here is an example, using the same example from here, just ported into Arduino code:

#include <stdarg.h>
#include <stdio.h>

/* this function will take the number of values to average
   followed by all of the numbers to average */
float average ( int num, ... )
{
    va_list arguments;                     
    float sum = 0;

    /* Initializing arguments to store all values after num */
    va_start ( arguments, num );           
    /* Sum all the inputs; we still rely on the function caller to tell us how
     * many there are */
    for ( int x = 0; x < num; x++ )        
    {
        sum += va_arg ( arguments, double ); 
    }
    va_end ( arguments );                  // Cleans up the list

    return sum / num;                      
}


void setup() {
  Serial.begin(9600);
}

void loop() {
  float avg = average( 3, 12.2, 22.3, 4.5 );
  Serial.println(avg);
  avg = average( 5, 3.3, 2.2, 1.1, 5.5, 3.3 );
  Serial.println(avg);
  
  delay(1000);
}

Python: converting a string representing an hexadecimal integer representation into an int variable

Submitted by fabio on Wed, 2010-08-11 18:27.

Recently I had the need to convert a string containing the hexadecimal representation of an integer into an integer variable.

Eg, with something like FFAA, create an integer variable with the value of 65450.

In some programming languages there is an unhex() function but not in python.

In order to do so you'll need to use int(). If called with two arguments, int() expects the first to be a string representing a number in some base and the second to be the base.

Hey Arduino, say hello to the world!

Last updated on Mon, 2010-07-12 19:15. Originally submitted by fabio on 2010-06-09 12:54.

Ok, here we are. As any programmer knows, the first thing you have to do in order to learn a new programming language / environment is trying to print or display some simple text, usually the words Hello World.

Unfortunately, a stock Arduino doesn't have any screen so it's pretty common to connect an LED to the Arduino and just blink it. This is how microcontroller programmers are used to say hello world!