/* * This code (shamelessly copied from Arduino and modified for micro:bit) will print doubles to the uBit.serial * * Print.cpp - Base class that provides print() and println() * Copyright (c) 2008 David A. Mellis. All right reserved. * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Modifications by Matthew Ford, Copyright(c) 2015 Forward Computing and Control Pty. Ltd. */ #include "MicroBit.h" MicroBit uBit; size_t printFloat(double number, uint8_t digits); int main() { uBit.init(); uBit.display.print("Start"); // wait a bit so you can open terminal uBit.serial.printf("test of printf d format %d\n",(int)10); printFloat(0.0010,5); uBit.serial.printf("\n"); //uBit.serial.printf("test of printf e format %e\n",(double)10.0); These do NOT work DO NOT use //uBit.serial.printf("test of printf f format %f\n",(double)10.0); These do NOT work DO NOT use release_fiber(); // finished with setup, release the fibers!! } size_t printFloat(double number, uint8_t digits) { size_t n = 0; if (isnan(number)) return uBit.serial.printf("nan"); if (isinf(number)) return uBit.serial.printf("inf"); if (number > 4294967040.0) return uBit.serial.printf("ovf"); // constant determined empirically if (number <-4294967040.0) return uBit.serial.printf("ovf"); // constant determined empirically // Handle negative numbers if (number < 0.0) { n += uBit.serial.printf("-"); number = -number; } // Round correctly so that print(1.999, 2) prints as "2.00" double rounding = 0.5; for (uint8_t i=0; i 0) { n += uBit.serial.printf("."); } // Extract digits from the remainder one at a time while (digits-- > 0) { remainder *= 10.0; int toPrint = int(remainder); n += uBit.serial.printf("%d",toPrint); remainder -= toPrint; } return n; }