I'm trying to receive a char from Wire1 and convert it to float so i can interpret it. When I print the char to the serial monitor I see that it's reading in correctly (looks like this: "1.17" or "256.47")
However, when I try to use atof to convert it to a float and then print that float, all i ever get is "0.00"
Here's what the code looks like.
#include <stdlib.h> //do I even need this?
#include <i2c_t3.h>
char c[8]; int knob1x; float knob1;
void setup()
{
Wire1.begin();
Serial.begin(9600);
}
void loop()
{
Wire1.requestFrom(0x05, 8);
while(Wire1.available())
{
c[8] = Wire1.read();
knob1 = (float)atof(c);
Serial.print(knob1); i need this to print the float but it only prints "0.00"
//Serial.print(c[8]); this prints the number as char
Serial.print(" ");
}
delay(100);
}
The only information being sent through Wire1 are the numbers and the decimal point, so atof shouldn't be detecting any unrecognized symbols.
Is there any other useful method to convert char c[8] to float knob1?
Well, first, c[0] to c[7] are undefined, and second, this array doesn't necessarily end with the required '\0' char that will tell atof where the string ends...
if those issues were corrected do you think this will work?
sorry, arrays are always confusing to me and if i'm not constantly using them i forget how they operate.
and what exactly are you saying about "required '\0' char" i don't recall reading about that when reading about atof. could you tell me how to implement that or link a simple example?
giantsquid:
if those issues were corrected do you think this will work?
sorry, arrays are always confusing to me and if i'm not constantly using them i forget how they operate.
and what exactly are you saying about "required '\0' char" i don't recall reading about that when reading about atof. could you tell me how to implement that or link a simple example?
atof() expects a c-style string, which is C language is simply an array of chars; however, to mark the end of the string you need to put the null char '\0', otherwise the function will not know where to stop.
Also, when assigning to c[8], you're actually telling the program to populate only the eighth character in the array - the others are left untouched. And what's worse, since the array itself is defined as c[8], it's valid indexes only go up to 7, and writing to 8 probably runs over some other variable.
to allow for the extra termination character of the string.
c[8] = Wire1.read();
That writes each byte to the same location in the array.
You need to write the first character read to c[0], the second to c[1] etc
When you have read all the characters and put them in the array do