Pages: [1]   Go Down
Author Topic: Problem with simple multiplication  (Read 2324 times)
0 Members and 2 Guests are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 4
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I'm trying to use an A/D pin, read the value, simply multiply by 1000, and display the result back at the computer.  I'm using long for the big integer I'm making, but to no avail.

Here is the code:

Code:
int inputPin = 0;               // Analog Input pin #
int inputValue = 0;
long result;

void setup()
{
  Serial.begin(9600);           // open serial port, set to 9600 baud.
}

void loop()
{
  delay(1000);                          // waits for a second
  
  inputValue = analogRead(inputPin);    //Read input value
  result = inputValue*1000;             // Convert to bigger number

  Serial.print("inputValue is: ");      //Display input value
  Serial.println(inputValue,DEC);
    
  Serial.print("result is: ");          //Display result of multiplication
  Serial.println(result,DEC);
  
  Serial.println();
}

Here is the output (just a sample of it):

Code:
inputValue is: 137
result is: 5928

As you can see, if the inputValue is 137, the result is obviously wrong.

Any ideas at what I'm doing wrong?  BTW: I'm using the ATMega168, and Arduino 0006 to write the software.

Thanks,

Garrett
Logged

Forum Administrator
Cambridge, MA
Offline Offline
Faraday Member
*****
Karma: 12
Posts: 3538
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

It might be that because the two numbers you're multiplying are both int's, the result is calculated as an int before being stored in result.  You might try appending an "L" to the end of the 1000:

Code:
 result = inputValue*1000L;
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 4
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Ah, fixed it myself.. The line that says:

Code:
result = inputValue*1000;

Should be:

Code:
result = inputValue*1000L;

Since both 'inputValue' and '1000' were considered 'int' type variables, the program lopped off some bits before assigning it to 'result'.  

Fix: Force '1000' to be a long type of number by using '1000L'.

Sorry, I'm a noob to C.  Hope this helps others too.

  - - Garrett
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 4
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Looks like you beat me to the post button Mellis, thanks though  smiley
Logged

Pages: [1]   Go Up
Jump to: