Pages: [1]   Go Down
Author Topic: Need Help to Explain this Code  (Read 238 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Jr. Member
**
Karma: 0
Posts: 72
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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:
#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
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 616
Posts: 49433
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Offline Offline
Jr. Member
**
Karma: 0
Posts: 72
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Can you explain about that formula please?

Thanks You..
Logged

Global Moderator
UK
Offline Offline
Brattain Member
*****
Karma: 302
Posts: 26349
I don't think you connected the grounds, Dave.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Code:
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.
Logged

"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.

Pages: [1]   Go Up
Jump to: