Go Down

Topic: workaround for M0 dtostrf and float sprintf  (Read 154 times) previous topic - next topic

dsyleixa

Jun 21, 2018, 04:52 pm Last Edit: Jun 21, 2018, 05:57 pm by dsyleixa
hello,
I just received my new M0 Board (a Adafruit ItsyBitsy M0), and could not make sprintf and/or dtostrf work (SAMD Boards installed correctly).

Then I found this piece of code which I c+p'ed into my Sketch - and now surprisingly  both sprintf and dtostrf work fine. But I am curious about 2 things:
1) how does that snippet  make both functions work, especially sprintf for fp?
2) do I always have to c+p it or is there also a way by a #include <....> ?

Snippet:

Code: [Select]
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

char *dtostrf(double val, signed char width, unsigned char prec, char *sout);

#ifdef __cplusplus
}
#endif


complete code:
Code: [Select]
//


#pragma once

#ifdef __cplusplus
extern "C" {
#endif

char *dtostrf(double val, signed char width, unsigned char prec, char *sout);

#ifdef __cplusplus
}
#endif


int i=12345;
int32_t l=1234567890;
float  p=3.14159265358979323846;  // 20 Nachkommastellen
double e=2.71828182845904523536;  // 20 Nachkommastellen
char buf[30];

void setup() {
  // Serial output in setup() unvisible
  Serial.begin(115200);

  delay(1);
  Serial.println("sprintf Test\n");
  sprintf(buf, "i=%d", i); Serial.println(buf);
  sprintf(buf, "l=%ld", l); Serial.println(buf);
  sprintf(buf, "f=%25.20f", p); Serial.println(buf);
  sprintf(buf, "e=%25.20f", e); Serial.println(buf);
  delay(1);
}

void loop() {
  // Serial output works
  sprintf(buf, "i=%d", i); Serial.println(buf);
 
  sprintf(buf, "l=%dl", l); Serial.println(buf);
 
  sprintf(buf, "f=%25.20f", p); Serial.println(buf);
  dtostrf(p,25,20,buf);  Serial.print("  ");  Serial.println(buf);
 
  sprintf(buf, "e=%25.20f", e); Serial.println(buf);
  dtostrf(e,25,20,buf);  Serial.print("  ");  Serial.println(buf);

 
  delay(10000);

}

Go Up