<?xml version="1.0" encoding="utf-8"?>
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
<link rel="alternate" type="text/html" href="https://gamma.unpythonic.net/"/>

<title>Jeff Epler's blog</title>
<modified>2021-10-30T21:12:03Z</modified>
<tagline>Photos, electronics, cnc, and more</tagline>
<author><name>Jeff Epler</name><email>jepler@unpythonic.net</email></author>
<entry>
<title>Use printf() in Arduino programs</title>
<issued>2021-10-30T21:12:03Z</issued>
<modified>2021-10-30T21:12:03Z</modified>
<id>https://gamma.unpythonic.net/01635628323</id>
<link rel="alternate" type="text/html" href="https://gamma.unpythonic.net/01635628323"/>
<content type="text/html" mode="escaped">


&lt;p&gt;Are you happiest with printf() debugging?  Do circumstances lead to you
writing &amp;quot;arduino code&amp;quot; because it's just about the easiest way to set up
an embedded software project that's not to different from C(++)?  I have
something for you.

&lt;p&gt;I've only tested it on a sample of 1 board (the &lt;a href=&quot;https://www.adafruit.com/product/3857&quot;&gt;Adafruit Feather
M4 Express&lt;/a&gt;) but I suspect that
it works on a wide variety of &lt;strong&gt;arm-based&lt;/strong&gt; (or, actually,
newlib-based) boards.

&lt;p&gt;Long story short, put the following code in your &lt;strong&gt;.ino&lt;/strong&gt;
file, call &lt;code&gt;Serial.begin()&lt;/code&gt; as usual, then use 
&lt;code&gt;printf(...)&lt;/code&gt; and &lt;code&gt;fprintf(stderr, ...)&lt;/code&gt; just
like you would anywhere.  The only caveat I've discovered so far is that
printing floating-point numbers didn't work for me.

&lt;p&gt;&lt;pre&gt;
// This bridges from stdio output to Serial.write
#include &amp;lt;errno.h&amp;gt;
#undef errno
extern int errno;
extern &quot;C&quot; int _write(int file, char *ptr, int len);
int _write(int file, char *ptr, int len) {
    if (file &amp;lt; 1 || file &gt; 3) {
        errno = EBADF;
        return -1;         
    }                
     
    if (file == 3) { // File 3 does not do \n -&gt; \r\n transformation
        Serial.write(ptr, len);
        return len;
    }
     
    // color stderr
    static bool stderr_flag;    
    bool is_stderr = (file == 2);
    if (is_stderr != stderr_flag) {
        if (is_stderr) {
            Serial.write(&quot;\033[95m&quot;);
        } else {
            Serial.write(&quot;\033[0m&quot;);
        }
        stderr_flag = is_stderr;
    }

    int result = len;
    for (; len--; ptr++) {
        int c = *ptr;
        if (c == '\n')
            Serial.write('\r');
        Serial.write(c);
    }
    return result;
}

extern &quot;C&quot; int write(int file, char *ptr, int len);
int write(int file, char *ptr, int len) __attribute__((alias(&quot;_write&quot;)));
&lt;/pre&gt;
</content>
</entry>
</feed>
