by

An Arduino Calculator

The program below is capable of summing a sequence of single digit numbers typed into the Arduino IDE serial terminal. For example, if

2+4-5+1=

where typed into the terminal the output would be

2+4-5+1=2

Upload this program to your Arduino board and try it out. Notice that the program breaks if the very strict syntax is not obeyed.

// Serial Summation

// This program can calculate the sum of a sequence of single digit 
// numbers typed into the serial terminal.

byte myByte; // a variable to store a byte read from the serial 
// buffer
long mySum; // a variable to hold the sum of the numbers read in from
// the serial buffer
int myNum; // a variable to hold the number being read in from the
// serial buffer

void setup() {
  Serial.begin(9600); // begin serial communications
}

void loop() {
 
 mySum = 0;
 myNum = 0;
 
 if (Serial.available()>0) {
  while(Serial.available()>0){ // while bytes remain in the 
  //serial buffer
  
    myByte = Serial.read(); // read in the current byte
  
    // = is ASCII character 61
    // 0-9 are ASCII characters 48 to 57
    // - is ASCII character 45
    // + is ASCII character 43
  
    if (myByte == 61) { // equal sign found - could also do 
    /// if(myByte == '=')
      Serial.print('='); delay(5); // need a short delay so the 
      // Serial.print doesn't garbble subsequent calculations
      Serial.println(mySum); delay(5);
    }
    if (myByte >= 48 && myByte <= 57) { // found the first number
      myNum = myByte-48;
      mySum = myNum;
      Serial.print(myNum); delay(5);
    }
    if (myByte == 45) { // found a minus sign
      myByte = Serial.read(); // read in the next byte
      myNum = myByte-48; // since ASCII number have codes of 48 to 
      // 57, this will convert to the decimal equivelent
      Serial.print('-'); delay(5);
      Serial.print(myNum); delay(5);
      mySum = mySum - myNum; // subtract from total
    }
    if (myByte == 43) { // found a plus sign
      myByte = Serial.read(); // read in the next byte
      myNum = myByte-48;
      Serial.print('+'); delay(5);
      Serial.print(myNum); delay(5);;
      mySum = mySum + myNum; // add to total
    }
   } 
  }
}

Assignment

A) Modify this program to make it capable of adding, subtracting, multiplying, or dividing (in sequence, not obeying the order of operations).
B) Modify this program to be able to add together two two-digit numbers.

Leave a Reply

Your email address will not be published.