Playing around with Arduino finally implemented the printf. The floating point library can be only enabled by modifying the IDE Utilizar float con sprintf() y derivados en Arduino.
/* simple implementation of printf for SoftwareSerial */
#include <SoftwareSerial.h>
#include <inttypes.h>
#define PD0 0
#define PD1 1
class mySerial : public SoftwareSerial {
public:
mySerial(uint8_t receivePin, uint8_t transmitPin,
bool inverse_logic = false) :
SoftwareSerial(receivePin, transmitPin,inverse_logic) {}
virtual size_t write(uint8_t byte) {
return SoftwareSerial::write(byte);
}
int printf(char* fmt, ...) {
char buff[256];
va_list args;
va_start(args, fmt);
int return_status = vsnprintf(buff, sizeof(buff), fmt, args);
va_end(args);
uint8_t *s = (uint8_t *)&buff;
while (*s) write(*s++);
return return_status;
}
};
mySerial m(PD0,PD1);
void setup() {
m.begin(9600);
m.print("Hello from Arduino!\n");
m.printf("%s 0x%x %d %4o\n", "Hello", 0x80, 333, 128);
m.printf("%16s x\n", "Hello");
m.printf("%08x %e\n", 0x1234, 1e-10);
m.printf("Floats:\n");
m.printf("%.3lf %e\n", 3.14159f, 3.14159f);
}
void loop() {
}
If you use the Arduino Makefile
add following line to enable printf.
LDFLAGS += -Wl,-lprintf_flt,-u,vfprintf
The Output
Hello from Arduino! Hello 0x80 333 200 Hello x 00001234 1.000000e-10 Floats: 3.142 3.141590e+00
Comments are closed, but trackbacks and pingbacks are open.