I'm developing a program to calculate static margin of an aircraft through the calculations of mass,moment and arm. Essentially dealing with large numbers.
I'm having difficulty in setting up my code in the way so that the arithmetic is applied correctly to larger numbers. What I have so far works but only when the input is 0-9. The arithmetic fails to calculate digits beyond.
I understand that I'm breaking the digits into separate variables as to convert them from ASCII format to their intended value. The problem is in putting those digits back together.
I know this is probably very simple but I'm picking up arduino again after a long break and I'm very rusty.
Here's my code thus far:
long batterymoment,num1,num2,answer;
int batterymass = 720;
int batteryposition;
boolean mySwitch = false;
void setup() {
Serial.begin(9600);
num1=0;
num2=0;
Serial.println("Enter battery position");
}
void loop() {
while (Serial.available()){
batteryposition = Serial.read();
if(batteryposition>47 && batteryposition<58){
if(!mySwitch){
num1=(num1*10)+(batteryposition-48);
}else{
num2=(num2*10)+(batteryposition-48);
}
}
answer=num1+num2;
batterymoment=answer*batterymass;
Serial.print("Battery moment is: ");
Serial.println(batterymoment);
num1=0;
num1=0;
mySwitch=false;
}
}
Thanks.
-
1Read and understand this before you go any further: hackingmajenkoblog.wordpress.com/2016/02/01/…Majenko– Majenko2016年03月09日 18:35:27 +00:00Commented Mar 9, 2016 at 18:35
-
will do @MajenkoJertise– Jertise2016年03月09日 18:38:29 +00:00Commented Mar 9, 2016 at 18:38
1 Answer 1
Do you mean to repeat num1=0; in loop()?
It is only reading one character per loop() because loop() happens much faster than Serial.available() and Serial.read().
Do the reporting and clearing when you receive some sort of separator/non-digit character.
-
so you mean have a statement that requires a non-digit character to be satisfied before 'answer=num1+num2'?Jertise– Jertise2016年03月09日 18:28:20 +00:00Commented Mar 9, 2016 at 18:28
-
1Yes. You should be able to add an else { ... } around the last chunk of code to make this work. It would probably be cleaner to copy the characters into a buffer and then do atol(), atoi(), atof()... etc. on the buffer after you know you have the whole message.Dave X– Dave X2016年03月09日 18:40:16 +00:00Commented Mar 9, 2016 at 18:40