in my micro-processing class we are working with Arduino, when running this program i should just get what integer I type in just to get it to multiply by 2. Simple, everyone is getting this to work, I even have copied over a sketch that is functioning properly on other computers, but when i run this on my laptop(win 10) or desktop(win 8) I get crazy answers. have tryed difrferent ports, cables, arduinos and even installed and uninstalled arduino program.
I input 2 and get in serial monitor it tells me i have entered 98, then it automatically repeats itself and says i entered 58. I enter 5 and it tells me i have enrtered 101 and the 58 right after.
so confused, not even instructor has any ideas why. Can anyone please help me. Grades depend on this
// project 13: multiplying by 2
int number;
void setup()
{
Serial.begin(9600);
}
void loop()
{
number = 0;
Serial.flush();
while(Serial.available() == 0)
{ //Serial.println(Serial.read());
// do nothing
}
while(Serial.available() > 0)
{
number = Serial.read()+ '0';
}
Serial.print("You entered: ");
Serial.println(number);
Serial.print( " multiplied by two is ");
number = number *2;
Serial.println(number);
}
Keep in mind what you get back from Serial.read() is an ASCII character. For example, if you type in the digiti character '2' into the Serial monitor, the ASCII code for '2', or 50, is what you get back. You're trying to correct for it with the "+ '0'" code, but it should be minus. Also, that only works for each digit. A little more flexible way is:
void setup()
{
Serial.begin(9600);
}
void loop()
{
char buffer[10];
int charsRead;
int number = 0;
while (Serial.available() > 0)
{
charsRead = Serial.readBytesUntil('\n', buffer, 9);
buffer[charsRead] = '\0'; // Make it a string
number = atoi(buffer); // Convert string to int
Serial.print("You entered: ");
Serial.println(buffer);
Serial.print( " multiplied by two is ");
number = number * 2;
Serial.println(number);
}
}
Also, please read the two posts by Nick Gammon at the top of this Forum for guidelines on posting source code here.
That sketch worked great, thanks. Just that I am perplexed how the exact same copy of the program will work properly on others machines, but not mine. We copied it off thumb drive to see if it was just my happening on my laptop. Only mine gave invalid results