Marco Ferraioli
Marco Ferraioli

Reputation: 152

Arduino multiplication error

Arduino not is able to multiply numbers from 40 onwards by 1000 for example

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

void loop() {
    float a = 60 * 1000;
    Serial.print(a);
}

the result is -5536 .-. ??? what ??

I need to convert seconds to milliseconds, but I do not know alternatives to multiplication by 1000

Upvotes: 0

Views: 3363

Answers (2)

frarugi87
frarugi87

Reputation: 2880

The problem is that you are

  1. taking a (signed) int and setting it to 60
  2. taking a (signed) int and setting it to 1000
  3. multiplying them, obtaining a signed int. This generates an overflow, so the result is -5536
  4. converting this number in a float; -5536 -> -5536.0

The solution? Since you want to deal with floats... Operate with floats!

float a = ((float)60) * 1000;
float a = 60.0 * 1000;

The two solutions are the same; the first converts (int)60 in a float, then multiplies it by (int)1000, which gives you (float)60000. The second tells the compiler that 60.0 is a float.

In both cases a float multiplied by an int gives you a float, so... No overflow!

Upvotes: 2

kirill
kirill

Reputation: 366

The problem is that Serial.print converts a to signed integer. Try this:

Serial.print((float)a);

or this:

#include "floatToString.h"
char buffer[25];
Serial.print(floatToString(buffer, a, 5));

Upvotes: 0

Related Questions