In this tutorial I am going to show you how to make a calculator using Arduino Mega 2560 but you can use any Arduino Board. This calculator use only UART module, to communicate with computer. You don´t need any extra parts.
Considerations
After opening the serial monitor, you should ensure that the 9600 and “newline” are selected, in the options in the bottom bar, as you can see in image below:
Code
As you can see in the code below, there is a function called “serialEvent ()”, this function is recognized by the native libraries of Arduino and therefore the name of this function can not be changed, otherwise it will not be recognized and the system will not work.
Copy the code bellow to your Arduino IDE project and save it. Then open serial monitor of IDE or any other and insert the numbers and operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
//variable declaration int value1; int value2; char operation = ""; float result = 0; int aux = 0; String inputString = ""; // a String to hold incoming data boolean nextInsertion = false; void setup() { // init Serial Port with baudrate = 9600 Serial.begin(9600); // reserve 100 bytes for the inputString: inputString.reserve(100); Serial.println("Calculator!!!"); Serial.println("Enter the first number!"); } void loop() { if (nextInsertion && aux == 0){ nextInsertion = false; aux++; // increment var value1 = inputString.toInt(); inputString = ""; // clear inputString Serial.print("value1: "); Serial.println(value1); Serial.println("Enter the operator (+, -, / or *)!"); } if (nextInsertion && aux == 1){ nextInsertion = false; aux++; operation = inputString[0]; //only first char inputString = ""; Serial.print("operation: "); Serial.println(operation); Serial.println("Enter the second number!"); } if (nextInsertion && aux == 2){ nextInsertion = false; aux++; value2 = inputString.toInt(); inputString = ""; Serial.print("value2: "); Serial.println(value2); } if (aux == 3){ /* compute */ aux = 0; switch( operation ) { case '*': result = value1 * value2; break; case '/': result = value1 / value2; break; case '+': result = value1 + value2; break; case '%': result = value1 % value2; break; case '-': result = value1 - value2; break; default: Serial.println( "Erro! Operacao indefinida!\r" ); return; } Serial.print("result: "); Serial.println(result); } } /* SerialEvent occurs whenever a new data comes in the hardware serial Port. This routine is independent of the loop(), but using delay inside loop can delay response. */ void serialEvent() { while( Serial.available() ) { // get a new byte: char inputByte = (char)Serial.read(); // add byte to the String inputString += inputByte; if( inputByte == '\n' || inputByte == '\r' ) { //next insertion nextInsertion = true; } } } |