const int ledPin = 12;

void setup(){
    pinMode(ledPin, OUTPUT);

void loop(){
    if (Serial.available()) {
        light(Serial.read() – '0');

void light(int n){
    for (int i = 0; i < n; i++) {
        digitalWrite(ledPin, HIGH);
        digitalWrite(ledPin, LOW);

by Oscar Liang

awesome little piece of code which taught me how to setup connection by serial. yet one part I don't understand fully. Why does this line:

light(Serial.read() – '0');

make the code run once, and this line an infinite times.


has this something to do with binary? I don't get why subtracting the string 0 would run the code once.

Thanks in Advance!


Serial.read() -'0'

Such code is often used to convert a character to a digit (e.g. int).

Like if the character is '2', than '2' - '0' = ascii 50 - ascii 48 = 2

However, if you use


the value will be 50 instead of 2.... maybe looping 50 times (or 48 to 58, for values 0 to 9) will give you the impression it runs infinite?

| improve this answer | |
  • oh wow Thank you, so that is just a way to convert to a int. Never knew that! – Anton van der Wel Jun 15 '17 at 14:31
  • Yes, it is a way to convert one digit (so a character from '0' to '9') to an integer. Nb if this answer is good, consider upvoting and accepting it as your answer. – Michel Keijzers Jun 15 '17 at 15:07
  • cant upvote yet. I don't have enough rep, but you will get it in the end :) – Anton van der Wel Jun 15 '17 at 20:44
  • Thanks for accepting. No problem (geen probleem). Enjoy programming! – Michel Keijzers Jun 15 '17 at 22:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.