Arduino Logo

Arduino Beginner’s Course Lesson 4– Reading and Writing Pin Values





You can download our e-book ‘Learn Arduino’ from this link

In previous lessons we used the digitalWrite to write to a pin or more precisely to switch a pin on and off. That is the simplest way of using a pin. In this lesson we will go though reading and writing values to pins both digital and analog.

So we need to settle somethings straight before we proceed here. Digital pins can only be set as HIGH and LOW. Reading them will also give HIGH and LOW so they are pretty straight forward. Digital pins cannot act as analog at least not in a simple way.

Analog pins can output voltage between 0v and 5v. It is specified from the value given to the analogWrite function. This ranges from 0-255, so in order to set the analog pin to 2.5v one needs to do simple proportion (255/5)*2.5. Reading an analog pin gives the same voltage range but in a different resolution. The values from reading a pin ranges from 0  to 1023. You need to remember these numbers as we write our sketches (you will remember after some mistakes 🙂 ).

On board we have all pins enumerated for us D2-D13 and A0-A5 or more. So it will be easy to identify them. I personally prefer referring to digital pins as 4, 6, 7, etc i.e. as integers. While for analog pins I usually use the arduino convention of A0,A1,A2 etc these are built in constants and are translated directly into integers representing the actual pins.

Enough talking for now lets get our hands a bit dirty. By now you should have noticed that when we need to use a pin we specify its usage in the setup function like pinMode(1,OUTPUT). This instructs the chip on how to prepare the pin for us. This is simple… if you need the pin to output a value set it to OUTPUT, if you need it to read a value set it to INPUT. This works for both digital and analog pins.



Some code to keep in mind.

  • pinMode(1,OUPUT); or pinMode(A1,OUPUT);
  • pinMode(1,INPUT); or pinMode(A1,INPUT);
  • digitalRead(1); gives us HIGH or LOW
  • digitalWrite(val); where val can be HIGH or LOW;
  • analogRead(A1); gives us a value between 0 and 1023
  • analogWrite(A1,val); where val can be set between 0 and 255

Some warnings when using pins. Please note that pins cannot handle high currents, all currents should be limited to under 20ma per pin. This means that you cannot short circuit pins without resistors. Also pay attention to LEDs. Never connect LEDs without a current limiting resistor. Typically on a 5v supply an LED will require a resistor of 300 ohms or so. Please use the formula V=IR to check your circuit before you switch it on as it might burn your chip.

Stay tuned for the next lesson.

Go to Lesson 5 here

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *