Go Down

Topic: Floating Point Fail? (Read 1 time) previous topic - next topic


Sep 17, 2009, 05:48 am Last Edit: Sep 17, 2009, 05:49 am by ziplock Reason: 1
Here's some code I wrote (working on a matrix library, gotta start somewhere).

I'm just testing my code with serial input, and apparently now 3.14 time 1 equals 150.84! Someone, please try my code, I have no clue what's wrong!
Code: [Select]
#include <math.h>

double matrixa = 3.14;
double matrixb;
double matrixc;
double matrixd;
double val = 0;
double holdVal;

void setup() {
 matrixc = 3;
 matrixd = 6.47;

void loop() {
 if(Serial.available() > 0) {
   matrixb = Serial.read();


void matrixmult() {
 holdVal = matrixa * matrixb;
 val = holdVal;//*(matrixc*matrixd);


   matrixb = Serial.read();
Serial.read() reads raw characters and returns an "int" value.  If you were to type in a "1" in the serial monitor field, Serial.read() will return the ascii value of the "1" character, which is 49.  I'm not sure exactly where 150.84 comes from, but it's "close" to what I'd expect...  (I get 153.86 when I run this on my system.)

If you want to type 1.234 in the serial monitor and have the arduino end up with 1.234 in a float variable, you'll have to do some additional work.  (hmm.  You'd think there would be a library that covers this sort of thing, but I don't recall one...)


Sep 17, 2009, 08:30 pm Last Edit: Sep 17, 2009, 08:51 pm by AlphaBeta Reason: 1
/me had some fun again...


#include <StringToAnything.h>

StringToAnything<float,8> readFloat;

void setup(){

void loop(){
  if (Serial.available()){
    int in = Serial.read();
    if (in!=' '){
      readFloat += in;
    } else {
      Serial.println( readFloat.convert() );
      readFloat = ""; //reset

You can also do this:

#include <StringToAnything.h>

StringToAnything<float,8> converter;

void setup(){
  converter = "1000101";
  Serial.print("1000101 is: ");

void loop(){/*nothign to loop*/}

If you only want to use this as a converter on already compiled char arrays.

You can use DEC BIN OCT and HEX when converting. This is when you tell the StringToAnything object what kind of format the string is.
123 can be:
DEC = 123
BIN =  1 (binary mode rejects 23)
OCT = 83
HEX = 291

Additionally you can indicate negation by beginning the string with a '-' such as "-23.34" will evaluate to the negative float -23.34 is the StringToAnything is setup correctly for it, like this:
Code: [Select]
StringToAnything<float,5> sta = "-23.34";
float f = sta.convert();

The number five in the declaration is because you will need to allocate space for the '-' in addition to each number.
I might eliminate this need on request.

Go Up