Skip to content
Dimitris Platis edited this page Feb 16, 2015 · 20 revisions

Introduction

Here some typical cases of the library usage will be demonstrated. Feel free to use and adjust them at your own will. These examples are also included in the Smartcar Sensors library, under the /examples folder.

Examples

###Sonar In this example, we collect data from two different ultra sound sensors that operate simultaneously and display the results of their measurements in centimeters, via the Serial port. The sensors are instantiated before the setup() function, then inside the setup() they are attached to their respective pins and finally in the loop() we collect their data every 100 milliseconds.

#include <Smartcar_sensors.h>

Sonar frontSonar, backSonar; //initialize two ultra sound sensors
const int FRONT_TRIG_PIN = 38; //sensor's trig pin
const int FRONT_ECHO_PIN = 39; //sensor's echo pin
const int BACK_TRIG_PIN = 40;
const int BACK_ECHO_PIN = 41;

void setup() {
  frontSonar.attach(FRONT_TRIG_PIN, FRONT_ECHO_PIN); //initialize the sensor with attach(trigger pin, echo pin)
  backSonar.attach(BACK_TRIG_PIN, BACK_ECHO_PIN);
  Serial.begin(9600); //start the serial
}

void loop() {
  delay(100); //run the following every 100ms
  Serial.print("Front: ");
  Serial.print(frontSonar.getDistance()); //print the distance in centimeters
  Serial.print(" Back: ");
  Serial.println(backSonar.getDistance());
}

###Sharp_IR In this example, we collect data from an SHARP infra red sensor and display the results of the measurements in centimeters, via the Serial port. The sensor is instantiated before the setup() function, then inside the setup() it is attached to its respective analog pin and finally in the loop() we collect its data every 100 milliseconds.

#include <Smartcar_sensors.h>

Sharp_IR frontIR; //instantiate the infra red sensor
const int IR_pin = A5; //set the pin that the infra red sensor will be providing data to

void setup() {
  frontIR.attach(A5); //attach (initialize) the sensor at the appropriate pin
  Serial.begin(9600); //start the serial
}

void loop() {
  delay(100); //run the following every 100 ms
  Serial.println(frontIR.getDistance()); //print the distance in cm
}

Clone this wiki locally