This simple program enable LPC11U24 MBED board to act as a simple integer calculator. Just type the operation you want to execute from the serial terminal. Admitted operations: +, -, * /, ^ (only positive exponent). Multiple operations in raw are supported as well as negative integer.
Fork of Serial_HelloWorld_Mbed by
Diff: main.cpp
- Revision:
- 3:3bef1c4e42d4
- Parent:
- 2:0baf535ed8f8
- Child:
- 4:235e50314809
--- a/main.cpp Mon Sep 22 04:29:44 2014 +0000 +++ b/main.cpp Mon Sep 22 06:23:35 2014 +0000 @@ -25,7 +25,7 @@ // check if the input is valid bool si_check_valid(const char & input) { - if ( ( ( int(input) > 57) || ( int(input) < 48) ) && (input != '+') && (input != '-') && (input != '*') && (input != '/') && (input != '=') ) { + if ( ( ( int(input) > 57) || ( int(input) < 48) ) && (input != '+') && (input != '-') && (input != '*') && (input != '/') && (input != '^') && (input != '=') ) { return FALSE; } else { return TRUE; @@ -42,23 +42,23 @@ } } +char c; +char op = '='; +char operand [100]; +char buf[10]; +int result =0; +int result_copy=0; +int index = 0; +int ioperand =0; +bool first = TRUE; +bool sign_check = TRUE; +bool neg_operand = FALSE; +bool error=FALSE; -int main() +// serial interrup callback function +void callback() { - char c; - char op = '='; - char operand [100]; - char buf[10]; - int result =0; - int index = 0; - int ioperand =0; - bool first = TRUE; - bool sign_check = TRUE; - bool neg_operand = FALSE; - - pc.printf("LPC Integer Calculator!\n"); - while(1) { c=pc.getc(); //get serial input @@ -84,8 +84,8 @@ } else { ioperand = char_to_int(operand,index); } - neg_operand=FALSE; - + + if (first) { //First Operator result = ioperand; first = FALSE; @@ -99,22 +99,36 @@ result = int (result / ioperand); } else if (op == '*') { result = int (result * ioperand); + } else if (op == '^') { + if(!neg_operand) { + result_copy = result; + for(int i = (abs(ioperand) -1); i>0; i--) { + result *=result_copy; + } + } else { + pc.printf("ERROR:Negative exponent"); + error = TRUE; + } } if (c == '=') { // Operator = has been entered--> Print result and reset calculator for (int j =9; j>=0; j--) { buf[j]='\0'; } - sprintf(buf, "%d", result); - pc.printf("%s", buf); + if(!error) { + sprintf(buf, "%d", result); + pc.printf("%s", buf); + } pc.printf("\n\n"); pc.printf("Please enter a new operation\n"); first = TRUE; + error = FALSE; } } op = c; // assign the Operator index=0; // reset the operand sign_check = TRUE; // sign check activated + neg_operand=FALSE; } else { pc.putc(c); if (c=='-') { @@ -123,11 +137,19 @@ } else if (c=='+') { neg_operand=FALSE; sign_check = FALSE; - } else { - pc.printf("ERROR:Two consecutive Operators entered"); + } else { + pc.printf("ERROR:Two consecutive Operators entered"); + error = TRUE; } } } } } +int main() +{ + pc.attach(&callback,Serial::RxIrq); + + pc.printf("LPC Integer Calculator!\n"); + while (1) {} +} \ No newline at end of file