I have been trying to do some simple projects on my Arduino mega and for some reason, when using variables, basic arithmetic such as 4*3.14 will return an answer like 12.03 instead of 12.56.
float radius;
float pi = 3.14;
float area;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("Enter radius: ");
while(Serial.available() == 0){
}
radius = Serial.parseFloat();
area = pi*radius*radius;
Serial.println("The area is: ");
Serial.print(area);
Serial.println();
}
Above is a simple piece of code I was using. I have checked that the input from the user is correct and I have attempted to cast the variables as floats and change the order of operations but the problem persists.
This only occurs when using variables so I'm assuming I'm not familiar with some Arduino syntax that isn't present in typical c++.
Set the Line ending to "No Line ending" as a starting point
To try and track down what is going on with the calculation break the calculation into 2 steps, ie print the result of radius * radius then the result of area and for completeness print the value of pi
I've done this and it does not get me closer to an answer. It just shows that there is a basic error in the calculation. Like other replies have said, the code works fine on other boards.
What do you see if you print the intermediate result ?
What do you see if you increase the number of decimal places printed ?
What do you see if you print 2 * 2 ?
As suggested, start debugging by using more print statements. E.g
float radius;
float pi = 3.14;
float area;
void setup()
{
Serial.begin(115200);
}
void loop()
{
Serial.print("Enter radius: ");
while (Serial.available() == 0)
{
}
radius = Serial.parseFloat();
// debug
Serial.println(radius);
// more debug
Serial.print("Radius square: ");
Serial.println(radius * radius);
area = pi * radius * radius;
Serial.print("The area is: ");
Serial.println(area);
Serial.println();
}
Output:
09:35:01.331 -> Enter radius: 2.00
09:35:04.341 -> Radius square: 4.00
09:35:04.341 -> The area is: 12.56
09:35:04.341 ->
09:35:04.341 -> Enter radius:
Notes
I've used a baudrate of 115200; your original sketch with 9600 also gave the correct results (as others have confirmed).
Are you using an original Mega or a clone. If the latter, what is the ttl-to-usb converter on the board? It's the IC closest to the USB port.
My board is a clone (Elegoo). The chip I believe you are referring to has:
"ATMEL"
"MEGA16U2"
"2401 TH"
"240 HCR"
Written on it.
Below is my result using your code as well. You can see that my inputs are being read in correctly but the multiplication by 3.14 is what is causing issues.
Enter radius: 2.00
Radius square: 4.00
The area is: 12.03
Enter radius:
Also, I increased the number of decimals printed and the result was:
Enter radius: 2.00
Radius square: 4.00
The area is: 12.03256060
Enter radius: