Is there a vprintf for the Serial class?

28 Aug 2012

Hi there, I'd like to implement a function like so:

void PrintfAt(int x, int y, string format, ...)
{
  //magic!
  MySerialObject.printf(format, passed_arguments);
}

All of the examples of doing this require something like vprintf, which can take a va_list object.

How could I implement such a function in mbed without rewriting printf?

28 Aug 2012

Hi,

Take a look at vsprintf(). that should be the magic you need!

Simon

30 May 2014

I am looking to do exactly the same thing. vsprintf() isn't included in the Serial library either!

09 Jun 2014

Hello, try this:

#include "mbed.h"
#include <string>
#include <cstdarg>

DigitalOut myled(LED1);
Serial serial_device(USBTX,USBRX);  // or other serial device

void PrintAt(const char* format, ...)
{
    char buffer[200]= {0};
    va_list argp;
    va_start(argp, format);
    vsnprintf(buffer,200,format, argp);
    va_end(argp);
    serial_device.printf("%s",buffer);
}

int main()
{
    serial_device.baud(9600);
    int count=1;
    while(1) {
        myled = 1;
        wait(2);
        PrintAt("Test #%i\n\r",count++);
        myled = 0;
        wait(2);
    }
}

Michael