The ² & ³ calculator

I wrote the code to find the ² and ³ of numbers. But it only works sometimes and sometimes it doesn't work. I am just a beginner.

commented.ino (1.89 KB)

Sorry, i just started using this forum. Here's the code:

int number;
int test;
long cubed;
long squared;

void setup() {
Serial.begin(9600);
Serial.println("");
Serial.println("* -The Amazing Square and Cube Calculator- *");
Serial.print("
");
Serial.println();
Serial.println("Instructions: ");
Serial.println("1) Type in the number that is to be squared and cubed in the Serial Monitor.;");
Serial.println("2) Voila, the square and cube of the number you typed will be displayed.");
delay(5000);
}

void loop() {
boolean error = false; // error is used when number cannot be used

while(Serial.available() == 0)
test = Serial.read() - '0'; // when there is something to read, save it into test

if(-1290 <= test <= 1290) { // is the number can be used
error = false;
number = test;
Serial.print("You typed '"); //display what was typed
Serial.print(number);
Serial.println("'");
}
else { //is the number can't be used
error = true;
number = test;
}

if(error == true) {
Serial.println("Make sure you typed a number between -1290 and 1290 without decimal points."); // printed if number can't be used
Serial.print("You typed '");
Serial.print(number);
Serial.println("'");
Serial.println("Please type the number again.");
}
else if(error == false) {
squarecube(); // calculate square and cube then add 3 empty lines
Serial.println();
Serial.println();
Serial.println();
}
while(Serial.available() > 0) { // flush all unwanted stuff
int dump = Serial.read();
}
}

void squarecube() {
squared = number * number; // calculate square and print
Serial.print(number);
Serial.print(" squared is ");
Serial.println(squared);

cubed = squared * number; // calculate cube and print
Serial.print(number);
Serial.print(" cubed is ");
Serial.println(cubed);
}

What happens when it "doesn't work"?

Is it repeatable? Are there certain values that don't work?

Thanks for the quick reply. Sometimes when i type a 2, it says i typed a different number. I also can't use more than 1 digit, it only reads the first digit.

What do you mean by "But it only works sometimes and sometimes it doesn't work"? Can you explain things more clearly - perhaps with an example - of when it works, and when it doesn't work?

That said, I see a few things which concern me:

  1. Line 22 - Serial.read() looks for incoming bytes (http://arduino.cc/en/Serial/Read) - you then subtract a single character '0' (see http://arduino.cc/en/Reference/Char) from a byte - since char '0' is the same as the decimal value of 48 (see http://www.asciitable.com/) - your value of test is being set to whatever is read, then subtracting 48 from that - so if you input 255, test would be set to 207. That probably isn't what you want...?

  2. Line 22 - your code seems to indicate that only a value between -1290 and 1290 (inclusive) will be accepted, yet you are only reading a byte from the serial port (a value 0 - 255). 'test' is an integer (so it can hold a value between -32768 and 32767 - so that's ok. But you are still only reading a byte in; if the user enters a number larger than what a byte can hold, you need to read in two bytes, then reassemble them in your while() loop. Instead, you read one byte, subtract the value of 48 (see above), then throw that away, and read the second byte (and subtract 48 from it). What you really need to do is prior to line 21, set test to 0 (to clear it out), then in line 22 you need to read the byte from the serial and update test with the previous value of test, and bitshift the new value into test (and add it to the old value of test), for each byte. I know that sounds complicated, and I can't readily explain what I mean - maybe somebody else here can help more on this.

  3. Line 24 - this looks wonky; what you really want here is something like:

if (test >= -1290 && test <= 1290) {

I am certain that line 24 compiles, and from a mathematical representation is correct - I am just not certain it will do what you are expecting it to do (which with the current code you can't easily test, because of the issues outlined above). For all I know, it may work perfectly, but the syntax isn't one I am familiar with in C/C++ (though I am familiar with it from a mathematical standpoint).

Everything else looks ok, otherwise.

Nanopixel5:
I also can't use more than 1 digit, it only reads the first digit.

That may be just a matter of format. Try this and see if you can work on from there. This is about using bluetooth, but the essential code is the same

/* This is a simple test for two way traffic via bluetooth 
   but you can try it first using the USB cable to the serial 
   monitor without the bluetooth module connected.
   
   Note that some bluetooth modules come set to a different baud rate.
   This means you need to alter the command
                Serial.begin(9600) accordingly
   Same goes for the setting in the bottom right corner on the 
   serial monitor */             

byte byteRead;

void setup()
{
    Serial.begin(9600);
    Serial.println("OK then, you first, say something.....");
    Serial.println("Go on, type something in the space and hit Send,");
    Serial.println("or just hit the Enter key, then I will repeat it!");
    Serial.println("");
}

void loop() {
   //  check if data has been sent from the computer: 
  if (Serial.available()) {
    /* read the most recent byte */
    byteRead = Serial.read();
    /*ECHO the value that was read, back to the serial port. */
    Serial.write(byteRead);
  }
}

When the code works, it is like this :
You typed '2'
2 squared is 4
2 cubed is 8

When it doesn't, it is like this:
You typed '-49'
-49 squared is 2401
-49 cubed is -117649

(i typed 2)

Nick_Pyner:
That may be just a matter of format. Try this and see if you can work on from there. This is about using bluetooth, but the essential code is the same

/* This is a simple test for two way traffic via bluetooth 

but you can try it first using the USB cable to the serial
  monitor without the bluetooth module connected.
 
  Note that some bluetooth modules come set to a different baud rate.
  This means you need to alter the command
                Serial.begin(9600) accordingly
  Same goes for the setting in the bottom right corner on the
  serial monitor */

byte byteRead;

void setup()
{
    Serial.begin(9600);
    Serial.println("OK then, you first, say something.....");
    Serial.println("Go on, type something in the space and hit Send,");
    Serial.println("or just hit the Enter key, then I will repeat it!");
    Serial.println("");
}

void loop() {
  //  check if data has been sent from the computer:
  if (Serial.available()) {
    /* read the most recent byte */
    byteRead = Serial.read();
    /*ECHO the value that was read, back to the serial port. */
    Serial.write(byteRead);
  }
}

Why did you use Serial.write? What is the difference between Serial.write and Serial.println?

while(Serial.available() == 0);
delay(10); //let the buffer fill up with the entire number
test = Serial.parseInt();

@cr0sh, I do not believe entering 255 in the monitor will return as 255, I think it will return 3 bytes '2','5','5'. Although I could be wrong...in which case dont bother reading this post

Nanopixel5:
When it doesn't, it is like this:
You typed '-49'
-49 squared is 2401
-49 cubed is -117649

Looks pretty kosher to me

I am trying to make a square and cube calculator, but it doesn't seem to be working. Does anybody know what is wrong with the code? Can someone help me? :sob:

This is the code:

int number;
byte incoming;
long cubed;
long squared;

void setup() {
Serial.begin(9600);
Serial.println("");
Serial.println("* -The Amazing Square and Cube Calculator- *");
Serial.print("
"); //print when sketch starts first time or resets
Serial.println();
Serial.println("Instructions: ");
Serial.println("1) Type in the number that is to be squared and cubed in the Serial Monitor.;");
Serial.println("2) Voila, the square and cube of the number you typed will be displayed.");
}

void loop() {
boolean error = false; // error is used when what is typed cannot be used, it prevents it from entering the if loop(at the end) and being squared and cubed
number = 0; //blank out number number from last time loop ran

while(Serial.available() == 0) // do nothing when nothing is typed

while(Serial.available() > 0) { //filter to remove anything which isn't a number
incoming = Serial.read();

if(incoming >= '0' && incoming <= '9') {
number = (number * 10) + (incoming - '0');
delay(5);
}
else{ //if it is not a number, display error messge and break out of while loop
errorWarn();
error = true;
break;
}
}

if(error == false) { //if it isn't a number it can't enter here
squarecube(); //calculate square and cube
}

while(Serial.available() > 0) { //clears serial buffer so extra stuff won't be in the buffer the next time the loop runs
Serial.read();
}

}

void squarecube() {
Serial.print("You typed '"); //display what was typed
Serial.print(number);
Serial.println("'");

squared = number * number; // calculate square and print
Serial.print(number);
Serial.print(" squared is ");
Serial.println(squared);

cubed = squared * number; // calculate cube and print
Serial.print(number);
Serial.print(" cubed is ");
Serial.println(cubed);

Serial.println();
Serial.println(); // add three empty lines
Serial.println();
}

void errorWarn() {
Serial.println("Make sure you typed a NUMBER WITHOUT DECIMAL POINTS."); //display error message
Serial.print("You typed '");
Serial.print(number);
Serial.println("'");
Serial.println("Please type the number again.");
Serial.println();
}

sketch_dec29c.ino (2.47 KB)

@Nanopixel5, do not cross post. Threads merged.

Look at the examples in serial input basics for a more robust way to receive data - especially example 2 and the code for parsing numbers

...R

int number;
byte incoming;
long cubed;
long squared;


void setup() {
  Serial.begin(9600);
}

void loop()

{
    while(Serial.available() > 0) {     //filter to remove anything which isn't a number
    incoming = Serial.read();

    if(incoming >= '0' && incoming <= '9') {            
      number = (number * 10) + (incoming - '0'); 
      delay(5);      
    }  
 Serial.print("number:");Serial.println( number);
 squarecube();
  
}
Serial.flush();
number=0;
}
void squarecube() {
  Serial.print("You typed '");  //display what was typed
  Serial.print(number);
  Serial.println("'");  

  squared = number * number;    // calculate square and print
  Serial.print(number);
  Serial.print(" squared is ");
  Serial.println(squared);

  cubed = squared * number;    // calculate cube and print
  Serial.print(number);
  Serial.print(" cubed is ");
  Serial.println(cubed);

  Serial.println();
  Serial.println();           // add three empty lines
  Serial.println();
}


void errorWarn() {
  Serial.println("Make sure you typed a NUMBER WITHOUT DECIMAL POINTS."); //display error message
  Serial.print("You typed '");
  Serial.print(number);
  Serial.println("'");
  Serial.println("Please type the number again.");
  Serial.println();
}

Check output it must work

I feel like nobody read my post...This should work just fine, keyword "should"

while(Serial.available() <= 0);
delay(1); //let the buffer fill up with the entire number
test = Serial.parseInt();

i think you havent read post. Parseint function will not work.

So upload my code & continue working

@AMPS-N But...I have used it before...with the serial monitor. I would type 0-100 in the monitor and Serial.parseInt() would return that number?

Can you explain why it would not work, maybe I am missing something.

I tried ur code .I used simple code from arduino inteself. Where i didn't get integer value.

I am thinking it might be issue with version Of IDE it support.So i have changed code where i am not using parseInt itself.

as per me if my code is working you should proceed with that.

share me latest code ur working using code tag<>. let me check again

This code works perfectly on 1.0.5, and should be faster and simpler

void setup()
{
  Serial.begin(115200);
}

void loop()
{
  if(Serial.available() > 0) //has a number been entered?
  {
    delay(5); //wait for the buffer to fill up
    int test = Serial.parseInt();
    Serial.println(test);
    while(Serial.available() > 0) //parseInt stops when the character is not a number or number is too big, this clears the buffer
      Serial.read();
  }
}

I attached pictures to show some proof :smiley:

i tried ur code its not working. So if it working on your IDE. i think it better you to sort out the issue.

For above code. the input given & output you expected are really matching???