SALES INQUIRIES: 1 (888) 767-9864

digitalRead() and Serial Port Communication

As simple as it may seem, knowing when something is either on or off can be a great tool to designing something useful.  Answers to the following questions are what this lesson plans to tackle:

  • Is a button being pressed?
  • Has a switch been turned on?
  • What is my on/off sensor status?

When you can answer questions like these, you can implement actions based on the current status – if the button is pressed do this – otherwise, do that.  If the sensor is HIGH take this action, otherwise do nothing.  You get the gist.  But before we can implement the actions, we have to be able to track the status and the changes of the digital pins.

You Will Need

  1. A momentary push button – this is a button that is spring loaded, so when you press it, it pops back out
  2. Jumper wires – at least three
  3. A 10,000 Ohm resistor AKA 10K resistor
  4. solder-less breadboard
  5. A very ripe banana, with one peel removed (not completely useful, but nutritious)

Step-by-Step Instructions

  1. Connect your push button to the breadboard.
  2. Connect one side of the push button to the 5-volt pin on the Arduino board using a jumper wire.
  3. Connect one side of the 10K resistor to the other side of the pushbutton.
  4. Connect the other side of the resistor to the ground pin on your Arduino.  You may have to use a jumper wire to make this reach.
  5. The same side you have your resistor connected to the pushbutton, connect a jumper wire  and run this to pin 2 on your Arduino board.
  6. Connect your Arduino to your computer with the USB cable.
  7. Go to File > Examples > 01.Basics > digitalReadSerial
  8. Click the Verify button in the top left corner. The verify button will turn orange and then back to blue when it has completed compiling.
  9. Click the Upload Button (to the immediate right of the verify button).  This button will also turn orange and then back to blue once you sketch is uploaded to your Arduino board.
  10. Now go to the menu bar at the top and select Tools > Serial Monitor.  You could use the short cut key of Shift + Control + M.
  11. The serial monitor window will open and will be spotting off numbers.  It should be a bunch of 0’s.
  12. Press and hold the pushbutton – watch the serial monitor window, the numbers should now be 1.
  13. If the numbers are not scrolling, make sure you click scrolling at the bottom left of the serial monitor window.

This image built with Fritzing.

Discuss the Sketch

Below is the full sketch that comes as an example fron the Arduino IDE.  It can be found at File > Examples > 01.Basics > digitalReadSerial

/*
DigitalReadSerial
Reads a digital input on pin 2, prints the result to the serial monitor

This example code is in the public domain.
*/

// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;

// the setup routine runs once when you press reset:
void setup() {
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
    // make the pushbutton’s pin an input:
    pinMode(pushButton, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
     // read the input pin:
     int buttonState = digitalRead(pushButton);
     // print out the state of the button:
     Serial.println(buttonState);
     delay(1); // delay in between reads for stability
}

This sketch opens up with a multi-line comment containing a short description of the program and circuit.  The first block of code is where we declare and initialize variables.  From the last lesson we are familiar with the int data type.

int pushButton = 2;  //This is the pin that our push button is connected to.

Notice how on one line the variable pushButton is declared and initialized.  Also notice the descriptive name of the pushButton – this is how it ought to be – variable name with meanings.

So let’s consider what we have done so far – we have made a variable that will store the pin number that our push button is connected to.

The next block of code we come to is the setup().  Inside these wily curly brackets there are two functions – one which we are already familiar, namely pinMode() and another which we will learn to love – Serial.begin().

Serial.begin() is part of a family of functions referred to as a library.  The name of the library is the Serial library. A library is just a group of functions that work towards a similar purpose.  If you had a Circus library, it might contain the functions juggle(), balance() and flamingCircleOfDeath().  To access the functions in a library you write the name of the library followed by the name of the function in the library, with a period in-between.

Circus.juggle();

Arduino has many built in libraries and many community contributed libraries.  You can check them all out here or Google for a specific library if you have a need.

So what does the Serial library do?

The Serial library helps you establish communication between your computer and the Arduino board.  If you ever go to marriage counseling, you will know that communication involves sending and receiving.  Data can flow both ways.  If we want to establish this communication, we use the begin() function from the Serial library.

Serial.begin(9600);

The begin() function takes one argument – the baud rate.  What is the baud rate you ask?  It is the rate at which data will flow between your computer and your Arduino.  And I will give you a short answer – for most Arduino sketches you will run, a baud rate of 9600 is what you will provide as an argument.

That’s all you really need to know about the baud rate to get started with serial monitoring.  But I have a feeling you want to know more, so if you check out the further reading section at the end of this tutorial, there will be some links to tempt your insatiable desire for acquiring an understanding of all things in the universe.

Moving on to the next function, we see our new friend again pinMode(). We want to set the mode of a pin and what is cool about pinMode this time around is that we are changing the arguments we pass to the function.  Instead of being an OUTPUT, we want our pin to be an INPUT, because we want to read voltage at this pin, not provide it.

pinMode(pushButton, INPUT) ;

Here we use the variable pushButton to let the function know we are setting the mode at pin 2.  Then we use the keyword INPUT, to say which mode we want.

Those are the only two functions in the setup() curly braces – and just as a reminder – setup() only runs once.

The next block of code is the function loop().  What do we see here?

int buttonState = digitalRead(pushButton);

Whooa!  What the heck is this?  It looks like they are declaring a variable?!  I thought that was at the top of the sketch – and you would be right for many sketches.  But actually, we can declare and initialize a variable any time we want in our program.  And we will see here shortly why this is the way to go.

So let us brake down this statement.  First let’s look at the data type and the name.  We are declaring an integer and we are calling it buttonState.  I bet you can guess what this variable is for – it will hold the state of our pushbutton.

To initialize the variable, we see something altogether new and awesome – we set the variable equal to the output of a function called digitalRead().  Now this is going to take a little recall power on your part.  Do you remember the reason of the word void in front of the loop() fuction?  We had to write void because the function loop() does not return a value.  But that is not the case for the function digitalRead().

The digitalRead() function returns an integer – either a 1 or a 0.  If it is a 1, than the voltage at the pin is high, if the value is 0, the voltage at the pin is low.  What pin you ask?  Well the pin you pass as an argument in the digitalRead() function.  In this case we send the variable pushButton, because we want to read the state of pin 2 (if you recall pushButton was initialized to equal 2).

All this in the following line of code:

int buttonState = digitalRead(pushButton);

This is why Arduino rocks – one line of code and you are on your way to dominating the world.

Now the state of our push button will be either HIGH (pressed) or LOW (not-pressed).  A HIGH will be reported as a 1, and a LOW will be reported as a 0.  When we press the pushbutton, pin 2 is exposed to the 5-volts from the Arduino board, this is considered HIGH, and the digitalRead() function will return a 1.  If the button is not pressed, then all that pin 2 is exposed to is the ground voltage which is 0 and digitalRead() will return 0.

The next line of code we come back to the Serial library for another function called println().

Serial.println(buttonState);

The Serial.println() function returns the value of whatever variable you stick in as an argument.   It will report this value to the serial monitor window on your Arduino IDE.  To open up the serial monitor window all you have to do is click Tools > Serial Monitor  (or SHIFT + CONTROL + M).  This is one way to retrieve the data on your Arduino board.

Keep in mind, that when you unplug your Arduino and use some batteries to charge it, the Serial.println() function won’t do you much good.  But while you are creating the circuit and the sketch, there is no better way to trouble shoot than use the println() and print() functions from the Serial library.

So lets cover what we have done so far in the loop.  First we read the state of digital pin 2 and save the state in a variable.  Then we display the state in the serial monitor window.

Finally we use the delay() function and wait one millisecond – this allows the reading at the pin to stabilize.

Once this is done, the loop starts from the top.  We read another value at pin 2 – we are checking every time whether the button is pressed or not pressed – this value gets assigned to our buttonState variable, then we display the newly recorded value to serial monitor window – again.  And we do this over and over – hundreds of times per second.

So go ahead, press that button, watch the serial monitor window – I think you are already brewing applications for these functions…

Try On Your Own Challenge

  • Change the function Serial.println() to Serial.print(), what happens to the output in the serial monitor window? Can you tell the difference between the two functions?
  • Change the pin that you are reading from to pin 3.  Make the circuit change and the changes to the sketch.

Further Reading