Re: Arduino Lesson 4 Code
by djadament on Thu Jan 05, 2012 3:53 pm
Well see thats the weird thing if you look into the lesson 4 on here it shows a problem where that happens.
/*
* Drive size calculator!
*/
int drive_gb = 100;
long drive_mb; // we changed the type from "int" to "long"
void setup() // run once, when the sketch starts
{
Serial.begin(9600); // set up Serial library at 9600 bps
Serial.print("Your HD is ");
Serial.print(drive_gb);
Serial.println(" GB large.");
drive_mb = 1024 * drive_gb;
Serial.print("It can store ");
Serial.print(drive_mb);
Serial.println(" Megabytes!");
}
void loop() // we need this to be here even though its empty
{
}
here it shows the problem that drive_gb starts as an int and then in the equation drive_gb makes a temp variable to store the answer of 1024 * drive_gb in an int also which causes the error in the answer. It then goes on to show the solution to the problem here:
/*
* Drive size calculator!
*/
int drive_gb = 100;
long drive_mb;
void setup() // run once, when the sketch starts
{
Serial.begin(9600); // set up Serial library at 9600 bps
Serial.print("Your HD is ");
Serial.print(drive_gb);
Serial.println(" GB large.");
drive_mb = drive_gb;
drive_mb = drive_mb * 1024;
Serial.print("It can store ");
Serial.print(drive_mb);
Serial.println(" Megabytes!");
}
void loop() // we need this to be here even though its empty
{
where you can see they moved drive_gb into drive_mb to convert it to a long then use the equation. The only thing I can think of is that the temp variable that the answer is saved to before stored in the final variable on the left side of the equation is whatever type the operand is on the right side of the equation.
long x;
long_a = 10000;
So X = 1024 * long_a
it would be a problem because the temp variable made for the right side equation would become an int because 1024 is an int.
but if i rearrange and do
X = long_a * 1024
then it would work because the temp variable is then casted to long.
let me know if this holds any water its driving me crazy!