Go Down

Topic: Need Help to Explain this Code (Read 286 times) previous topic - next topic

mamette

Hi, i am a beginner with arduino..
Yesterday i try to control servo with Visual Basic 2010 with some code that i found from:
http://maxatcurotek.blogspot.com/2010/03/controlling-servo-attached-to-arduino.html

And it works, but i still confused about the code, especially with this code:
Code: [Select]
switch(ch) {
           case '0'...'9':
               val = val * 10 + ch - '0';


i have searching for the explanation on arduino websites, forum and entire internet, but still don't get the explanation..
Can anyone help me?

And this is the complete code:

Code: [Select]

#include <Servo.h>

Servo myservo;

void setup() {

   myservo.attach(A0);
   Serial.begin(9600);
}

void loop() {

static int val = 0;

   if(Serial.available())
   {

       char ch = Serial.read();
           
       switch(ch) {
           case '0'...'9':
               val = val * 10 + ch - '0';
               
               break;
           case 's':
               myservo.write(val);
               val = 0;
               break;
       }

   }
}


Thank You

PaulS

Normally, you need to have a single value for a case statement, like '0'. On the Arduino, '0'...'9' is an extension that means any value from '0' to '9' triggers that case.

mamette

Thank You PaulS, but how about this formula:
Code: [Select]
val = val * 10 + ch - '0';

Can you explain about that formula please?

Thanks You..

AWOL

It isn't a formula, it is an assignment.
The way you tell the difference is that whilst
Code: [Select]
x = x + 1; makes sense to a programmer, it is clearly mathematically nonsensical - how can "x" be the same as "x + 1"?

Code: [Select]
val = val * 10 + ch - '0';

At the beginning of the day, "val" is zero.
An ASCII digit '0'..'9' is in the variable "ch".
Subtracting '0' from the value converts it to its decimal value.
So, '3' - '0' = 3, for example.
Now, take the previous value of "val" and multiply by ten, and add in the decimal value of the new character entered.

Imagine I'd type '1' and then '6'.

First time through, "val" would end up with the value 1.
Second time through, val = 1 * 10 + 6 = 16.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Go Up