Go Down

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


Hi, i am a beginner with arduino..
Yesterday i try to control servo with Visual Basic 2010 with some code that i found from:

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() {


void loop() {

static int val = 0;


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


Thank You


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.
The art of getting good answers lies in asking good questions.


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

Can you explain about that formula please?

Thanks You..


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

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131