LESSON 05 – DIGITAL WRITE

 

INTRO

 

In this lesson, we will learn how to work with Arduino’s pins to make a circuit.

 

PINS

 

Pins on the arduino are numbered.  There are 14 digital pins numbered 0 to 13.  There are 6 analog pins numbered 0 to 5.  There are also pins used to provide power to the circuit.

 

For now, we will focus on using the digital pins.

 

PIN MODE

 

Pins have to be designated either for INPUT or for OUTPUT.  We can designate a pin for input or output by using the pinMode() command. 

 

We need to provide the pin number and the mode (INPUT or OUTPUT).

 

Here is an example of setting pin #10 to OUTPUT:

 

     pinMode(10, OUTPUT);

 

AVOID PINS 0 AND 1

 

Pin 0 is labeled RX on the Arduino.  RX is short for Receiving Pin.

 

Pin 1 is labeled TX on the Arduino.  TX is short for Transmitting Pin.

 

You can use both these pins like all others as long as you do not use Serial.begin in your program.  Because we will be using Serial.begin, we will generally just avoid pins 0 and 1 for now.  So you should use pins 2 to 13 for projects.

 

KEYWORDS

 

The words INPUT and OUTPUT are called keywords.  This means that they have special meaning in the programming language and should not be used as variable names.

 

Two other keywords are HIGH and LOW.  We will see how to use them next.

 

SETTING A PIN HIGH/LOW

 

We can set a pin to either HIGH or LOW by using the digitalWrite() function.  It requires that we specify the pin number and the level (HIGH or LOW).

 

Here is an example of setting pin 10 to high:

 

     digitalWrite(10, HIGH);

 

The above statement will set pin 10 to 5V. 

 

SIMPLE CIRCUIT (TURNING ON AN LED)

 

Now that we know how to set a pin to 5V, we can create a simple circuit with the Arduino.

 

CODE

 

Inside setup, use the pinMode() to designated pin #10 as an output pin.  Then, set the pin to HIGH by using the digitalWrite() function.

CIRCUIT

 

Using a breadboard, connect pin 10 to the positive side of an LED.  Then connect the negative of that LED to a resistor.  Then connect the other side of the resistor back to a Ground pin (GND) on the Arduino.

 

RESULT

 

When you run the program, it turns on the LED.  Of course, the LED stays on for good.

 

If you want to turn it off, you can change the digitalWrite() statement to set the pin to LOW and run the program again.

 

ADDING DELAY

 

In the program above, we could have made the pin high, then waited for 1 second, then set that pin to low.  That would have made the LED blink once for a second.

 

 

TRY THIS…

 

PRACTICE PROGRAM/CIRCUIT 05

 

Connect and LED and a resistor between pin 12 and GND of the Arduino.

 

Write the program that will turn the LED on for 1 second and then off for 1 second and then on for 1 second and then off for 1 second.

 

Alteration

a)    Alter your program so that the LED goes on and off forever.  Hint: Use the loop() function.