Floating Point Fail?

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!

#include <math.h>

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

void setup() {
  Serial.begin(300);
  matrixc = 3;
  matrixd = 6.47;
}

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

  matrixmult();
  Serial.println(val);
  delay(1000);
}

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...)

/me had some fun again...
http://code.google.com/p/alexanderbrevig/source/browse/trunk#trunk/Arduino/Utilities/StringToAnything

#include <StringToAnything.h>

StringToAnything<float,8> readFloat;

void setup(){
Serial.begin(9600);
}

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(){
Serial.begin(9600);
converter = "1000101";
Serial.print("1000101 is: ");
Serial.println(converter.convert(BIN));
}

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:

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.
:slight_smile: