sparkfun / Arduino_Apollo3

Arduino core to support the Apollo3 microcontroller from Ambiq Micro
83 stars 37 forks source link

Feature request: printf padding/floating point #361

Closed adamgarbo closed 3 years ago

adamgarbo commented 3 years ago

Hi there,

In v2.x of the Apollo3 Core, Mbed OS is responsible for managing sprintf/printf (https://github.com/sparkfun/Arduino_Apollo3/issues/239). However, it appears that padding is no longer enabled. A simple example code snippet to print the date and time:

Serial.printf("20%02d-%02d-%02d %02d:%02d:%02d.%03d\n",
    RTC.year, RTC.month, RTC.dayOfMonth,
    RTC.hour, RTC.minute, RTC.seconds, RTC.hundredths);

Produces the following output:

But should have a number of zeros padding the values:

From what I can gather, this is due to the fact the Mbed core by default uses the minimal printf library to increase memory savings: https://github.com/ARMmbed/mbed-os/blob/master/platform/source/minimal-printf/README.md#usage

It would be great to have padding reenabled, as well as the ability to print floating-point values. Given the specifications of the Artemis, I believe the additional Flash/RAM requirements should be trivial?

Cheers, Adam

jerabaul29 commented 3 years ago

I usually include something like this in my projects, can this help?

#ifndef HELPERS
#define HELPERS

#include "Arduino.h"
#include "stdarg.h"

//--------------------------------------------------------------------------------
constexpr size_t serial_printf_max_buffer = 256;

// variadic serial print using printf formatting
void serialPrintf(const char *fmt, ...);

#endif

and the implementation:

#include "helpers.h"

void serialPrintf(const char *fmt, ...) {
  /* Buffer for storing the formatted data */
  char buff[serial_printf_max_buffer];
  /* pointer to the variable arguments list */
  va_list pargs;
  /* Initialise pargs to point to the first optional argument */
  va_start(pargs, fmt);
  /* create the formatted data and store in buff */
  vsnprintf(buff, serial_printf_max_buffer, fmt, pargs);
  va_end(pargs);
  Serial.print(buff);
}
jerabaul29 commented 3 years ago

(slightly adapted from a recipe found some time ago on a public github).

adamgarbo commented 3 years ago

Thanks @jerabaul29,

In Mbed OS, it's very simple to enable std-printf or mbed-printf with support for floating-point. For example, mbed_json.app just needs to have the following code added to enable standard printf.

    "target_overrides": {
        "*": {
            "target.printf_lib": "std"
        }
    }

Cheers, Adam

Wenn0101 commented 3 years ago

We have more than issue tracking this. closing in favor of https://github.com/sparkfun/Arduino_Apollo3/issues/278