You basiscally want a format string which includes %f
. However on Arduino, that only returns a ?
(not included to to space reasons). Refer to https://stackoverflow.com/q/27651012/5296568.
However the alternative is dtostrf
(double-to-string-formatted). The function takes the double
/ float
value, the total wanted width of the string and the decimal places you want to have.
However it fills the string with spaces to the left until the total width is met. You need an additional pass to replace it with 0
.
#include <Arduino.h>
void setup(){
Serial.begin(115200);
const float vals[] = {
1.2, 51.5, 61.8,
546.6, 255.0,
1235.9
};
//allocate 8 byte buffer
//biggest string is "-9999.9\0" (with NUL)
char buf[8];
int numVals = (int) (sizeof(vals) / sizeof(*vals));
for(int i=0; i < numVals; i++) {
//format correctly
dtostrf(vals[i], 4+1+1, 1, buf);
//convert left-appended spaces to zeroes
for(size_t j=0; j < sizeof(buf); j++){
if(buf[j] == ' ')
buf[j] = '0';
}
//print buffer
Serial.println(buf);
}
}
void loop() {
}
Prints
0001.2
0051.5
0061.8
0546.6
0255.0
1235.9
Edit: You can also offload it into a function and then feed it with the ADC values.
Example:
#include <Arduino.h>
void printValueFormatted(float value, int numDecimalPlaces, int totalWidth) {
//format correctly
char buf[16];
//prevent buffer overflow
if(totalWidth >= (int) sizeof(buf))
return;
dtostrf(value, totalWidth, numDecimalPlaces, buf);
//convert left-appended spaces to zeroes
for(size_t j=0; j < sizeof(buf); j++){
if(buf[j] == ' ')
buf[j] = '0';
}
//print buffer without newline
Serial.print(buf);
}
void setup(){
Serial.begin(115200);
}
void loop() {
float val = analogRead(0);
Serial.print("ADC Count: ");
Serial.print(val);
Serial.print(" -- Voltage: ");
val = val * 5.0f / 1023.0f;
printValueFormatted(val, 1, 4+1+1);
//print newline
Serial.println();
delay(100);
}
Prints
ADC Count: 719.00 -- Voltage: 0003.5
ADC Count: 718.00 -- Voltage: 0003.5
printf ("value - %04.1f\n", value);
and that will give you 4 digits before the DP padded with zeros and one after the DP. – Code Gorilla Jun 7 '18 at 11:36%f
specified does not work with Arduino provided functions likesnprintf
. – Maximilian Gerhardt Jun 7 '18 at 11:40