Hi,
I'm using an AT Mega2560 with a GPS module and a TFT screen.
In order to display the relative position on screen I need to convert an ASCII string of numbers into an integer.
To convert the ASCII number I have simply subtracted the value of "0" then multiplied it by 1,10,100 etc according to its position in the string.
This all works fine until a number greater than 3 is multiplied by 10,000 which gives a totally wrong result.
Multiplying by 100,000 then dividing by 10 gives the correct answer.
I have extracted the code and listed it below. This will print to console 4 sets of numbers, 2 with original code and 2 with corrected code.
This should cut and paste into the Arduino IDE.
Using the same code (changing the print functions) and compiling it with Code::Blocks to run on the PC gives fully working code.
I only have the AT Mega2560 so can't say if it works on any other Arduino.
I sure that the AT Mega I'm using is ok as other maths functions (sine, cos, tan etc) work fine.
Have I miss understood something or is this a bug in the compiler?
void setup() {
#include <string.h>
#include <ctype.h>
Serial.begin(9600);
char arr1[]={'3','3','3','3','3','3'}; //this works
char arr[]={'5','5','5','5','5','5'}; //this doesn't work
prnArray((char*)arr);
prnArray((char*)arr1);
prnArray1((char*)arr);
prnArray1((char*)arr1);
}
void loop() {
// put your main code here, to run repeatedly:
while(1);
}
void prnArray(char arr[])
{
int i=5;
long num=0;
num=num+(arr[i]-'0');
Serial.print(num,DEC);
Serial.println("");
i--;
num=num+((arr[i]-'0')*10);
Serial.print(num,DEC);
Serial.println("");
i--;
num=num+((arr[i]-'0')*100);
Serial.print(num,DEC);
Serial.println("");
i--;
num=num+((arr[i]-'0')*1000);
Serial.print(num,DEC);
Serial.println("");
i--;
num=num+(((arr[i]-'0')*10000)); //this is faulty
Serial.print(num,DEC);
Serial.println("");
i--;
num=num+((arr[i]-'0')*100000);
Serial.print(num,DEC);
Serial.println("");
}
void prnArray1(char arr[])
{ int i=5;
long num=0;
num=num+(arr[i]-'0');
Serial.print(num,DEC);
Serial.println("");
i--;
num=num+((arr[i]-'0')*10);
Serial.print(num,DEC);
Serial.println("");
i--;
num=num+((arr[i]-'0')*100);
Serial.print(num,DEC);
Serial.println("");
i--;
num=num+((arr[i]-'0')*1000);
Serial.print(num,DEC);
Serial.println("");
i--;
num=num+(((arr[i]-'0')*100000)/10); // the solution
Serial.print(num,DEC);
Serial.println("");
i--;
num=num+((arr[i]-'0')*100000);
Serial.print(num,DEC);
Serial.println("");
}