Hi I'm trying to work with incoming fractions like 0.1 or 0.9 but I think the "." character is causing an error. This is a sample of the code:
void loop()
{
if (Serial.available())
{
char c = Serial.read();
if (c == '?'){
char buffer[] = "000", *n = buffer;
while (*n != '\0')
{
char f = Serial.read();
//Check for numbers or the point '.' character for fractions
if (f >= '0' and f <= '9' or f == '.') //we should therefore be able to send upto "999" or down to 0.1
*n++ = f;
}
Serial.println(buffer);
pwm3Interval = atoi(buffer);
pwm3Interval*=1000;
Serial.print("pwm3Interval is now ");
Serial.println(pwm3Interval);
}
}
}
I'd like to be able to interpret incoming whole numbers up to 999 but also fractions.
I havent tested your code or looked at it deeply but the first thing that I thought off was shift left and right. If you know the max amount of decimal places, shift the decimal place the max number of times to the right and then when you recieve the number on the arduino, shift the number to the left.
eg: I know that I'll have at max 2 decimal places. I want to send 2.11 . I move the decimal place to the right 2 places (211) send the code to the arduino and tell my arduino to move the decimal 2 places to the left (2.11) voila!
void loop()
{
if (Serial.available())
{
char c = Serial.read();
if (c == '?'){
f = 1.2;
}
Serial.println(f);
}
}
This returns "1" to the console when I want "1.2". Presumably the character "." is causing problems but how can I work with such decimal point calculations?
if (f >= '0' and f <= '9' or f == '.') //we should therefore be able to send upto "999" or down to 0.1
*n++ = f;
That bit is wrong as well f is a character not a number so you need to turn it into a number fortunately if it is in the range 0 to 9 this is done by:-
// remove the or ="." from the if
number = f & 0x0f;
Then you shouldn't be adding it to n but doing this:-
n = (n * 10) + float(number);
but what if you have had a decimal point?
a logic variable "point" should be set as false at the start then:-
if(f == ".") point = TRUE;
so then the line above should read:-
if(point) n = n + (float(number) / 10); else n = (n * 10) + float(number);
That will handle just one decimal place if you want more you will have to keep track of how many numbers you have had in since the decimal point and use:-
n= n + (float(number) / (10*number_of_post_chars));