Lesson 2

Buttons, Distance Sensor and Displaying Data

>> Jump to: Button Module
>> Jump to: Arduino Libraries
>> Jump to: Ultrasonic Sensor
>> Jump to: Serial Monitor

Button ModuleBack to Top

Push-buttons or switches connect two points in a circuit when you press them.

This example turns on the built-in LED on pin 13 when you press the button that is connected to pin 4. When you are using the quick connect board, make sure you start counting from pin 0 to find pin 4.



int buttonPin = 4;
int ledPin =  13;

int buttonState = 0; // variable for reading the push button status

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin); // read the state of the push button value:
  if (buttonState == LOW) {
    digitalWrite(ledPin, HIGH); // turn LED on
  } else {
    digitalWrite(ledPin, LOW); // turn LED off:
  }
}


When the push button is unpressed there is no connection made, so the pin is connected to ground and circuit reads LOW turning the light off. When the button is pressed, it makes a connection, connecting the pin to 5 volts, so that we read a HIGH signal turning the light on. Some button modules operate in reverse to this logic, that is why we check for a "LOW" button state in the above example.




Once you've got a push button working, you often want to do some action based on how many times the button is pushed. To do this, you need to know when the button changes state from off to on, and count how many times this change of state happens. This is called state change detection. In this tutorial we learn how to check the state change, and we count the number of times the button was pressed and then decide if we want to turn an LED on and off.

int buttonPin = 4;
int ledPin =  13;

int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin); //read the state of the push button

  if (buttonState != lastButtonState) { //if the state has changed, increment the counter
    
    if (buttonState == HIGH) {
      //went from off to on
      buttonPushCounter++;
    }
    delay(50);
  }
  //save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;

  if (buttonPushCounter % 2 == 0) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
}


Pay attention to the value "2" in the above example code.
Changing the value will affect how many times the button is pushed before the LED is turned off and on.

  if (buttonPushCounter % 2 == 0) {
    digitalWrite(ledPin, HIGH);
  }
  else {
    digitalWrite(ledPin, LOW);
  }

Try changing this value and uploading your code.
Try 3, 4, 5, 6 or more to see what happens.

Arduino LibrariesBack to Top


The Arduino environment can be extended through the use of libraries, just like most programming platforms. Libraries provide extra functionality for use in sketches, e.g. working with hardware or manipulating data.

To use a library in a sketch,
select it from Sketch > Include Library.

A number of libraries come installed with the Arduino software automatically, but you can also download extra ones that work with your sensors. It is also possible to create your own library, but this isn't covered in RoboGames tutorials.


Read more about Arduino Libraries
https://www.arduino.cc/en/Reference/Libraries

Ultrasonic SensorBack to Top

Using the HC-SR04 Ultrasonic Distance Sensor

Small low-cost ultrasonic distance measurement modules like are an easy way to sense the presence of nearby objects and the distance to them. Often robots use these to sense objects or collisions and take appropriate action.

These Ultrasonic sensors have two transducers, basically a speaker and a microphone. Ultrasound is a high frequency sound.

A short burst of sound waves is sent out the "Transmit" transducer, then the "Receive" transducer listens for an echo. The time it takes for the signal to send and receive then calculates the distance. Including the “NewPing” library takes care of those calculations for us.




Read more about the "NewPing" library used with the Ultrasonic sensor.
https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home

Download the "NewPing" library - it will be required for the following example.
https://bitbucket.org/teckel12/arduino-new-ping/downloads/NewPing_v1.7.zip





Measuring in Centimeters
#include <NewPing.h>

int TriggerPin = 2;
int EchoPin =  3;

int Distance;

NewPing sonar(TriggerPin, EchoPin, 100); //setup Sensor pins and maximum distance 100.

void setup() {
  Serial.begin(9600);
}

void loop() {
  delay(100); //Wait 100 milliseconds
  Distance = sonar.ping_cm(); //get the data in centimeters
  Serial.print("Ping: ");
  Serial.print(Distance);
  Serial.println(" cm");  
}


Pay attention to which unit of measurement you are requesting.
If you want to get your distance in centimeters, use this code:

Distance = sonar.ping_cm();

If you want to get your distance in inches, use the following code instead:

Distance = sonar.ping_in();



Measuring in Inches
#include <NewPing.h>

int TriggerPin = 2;
int EchoPin =  3;

int Distance;

NewPing sonar(TriggerPin, EchoPin, 100); //setup Sensor pins and maximum distance 100.

void setup() {
  Serial.begin(9600);
}

void loop() {
  delay(100); //Wait 100 milliseconds
  Distance = sonar.ping_in(); //get the data in inches
  Serial.print("Ping: ");
  Serial.print(Distance);
  Serial.println(" in");
}

Serial MonitorBack to Top

Showing data from your Arduino is very important. It can be used to troubleshoot your code, see the values from your sensors and also to display important messages.

We recommended using "9600 baud" as a default in all examples unless otherwise noted.

You must choose the "baud rate" from the drop-down that matches the rate passed to Serial.begin in your sketch. This tells your program how fast to send the data and how fast to read the data. If these vales are mismatched, you will see odd characters on the screen because the two devices cannot understand each other. Simply change the values to match and the issue is resolved.

Note that on Windows, Mac or Linux, opening the Serial Monitor will cause your Arduino to reset and the sketch will start again from the beginning. To open the Serial Monitor window, click Tools > Serial Monitor.

In the "Ultrasonic Sensor" code, we use the following commands let the computer know that we want to communicate and set the "baud rate" speed:

void setup() {
  Serial.begin(9600);
}


In the "Ultrasonic Sensor" code, we use the following commands in your loop to write data to your computer screen:

Serial.print(); //print text to screen
Serial.println(); //print text to screen followed by a new line


These commands print data to the serial port as human-readable ASCII text.
The addition of "ln" will make it print carriage return character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n').

Writing Text to the screen with NO line breaks
Serial.print("Write this text to the screen. ");
Serial.print("Write some more text to the screen. ");
Serial.print("And some more on the same line.");

Looks like this:
Write this text to the screen. Write some more text to the screen. And some more on the same line.


Writing Text to the screen WITH line breaks
Serial.println("Write this text to the screen.");
Serial.println("Write some more text to the screen.");
Serial.println("And some more on a new line.");

Looks like this:
Write this text to the screen.
Write some more text to the screen.
And some more on a new line.


Use the following code to write a counter that increments every 1/2 second and will continue on forever. Each time you restart your Arduino, the count will reset to zero.

int counter = 0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  delay(500); //Wait 500 milliseconds
  Serial.println(counter); //show counter
  counter = counter + 1;
}

Try changing the delay and value to increment the counter.
Change the delay to 100, 1000, 2000, 5000
Change the increment value to 2, 3, 4, 5 (only whole numbers will work in this example)