Go Down

### Topic: Floating Point Fail? (Read 922 times)previous topic - next topic

#### ziplock

##### Sep 17, 2009, 05:48 amLast 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() {  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);}`

#### westfw

#1
##### Sep 17, 2009, 07:54 am
Quote
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...)

#### AlphaBeta

#2
##### Sep 17, 2009, 08:30 pmLast Edit: Sep 17, 2009, 08:51 pm by AlphaBeta Reason: 1

Quote

#include <StringToAnything.h>

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

void loop(){
if (Serial.available()){
if (in!=' '){
} else {
}
}
}

You can also do this:
Quote

#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:
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

Please enter a valid email to subscribe