Friday, April 12, 2013

Arduino Basic Robotics - Distance Sensing With HC-SR04 Ulrasonic Sensor

This will be an ongoing project that I'm going to be posting on, I'm working on finding the proper Fritzing parts (any help would be appreciated) to make a schematic so expect full code and schematics throughout the project.

Update: Here's the Google code library for the HC-SR04 sensor, you can get directions for adding new Arduino libraries here.

The Code



[sourcecode language="c"]
#include <NewPing.h>

#define SENSOR_LED 8 // sensor led pin
#define SENSOR_TIME 150 // sensor timing in ms
#define ECHO_PIN 1 // echo pin on ultrasonic sensor
#define TRIGGER_PIN 0 // trigger pin on ultrasonic sensor
#define MAX_DISTANCE 200 // max distance we want to ping for, in cm

// NewPing setup pins and maximum distance.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
Serial.begin(115200);
pinMode(SENSOR_LED, OUTPUT);
}

void loop() {
// get ping time in microseconds (uS)
unsigned int uS = sonar.ping();

// convert ping time to distance
if ((uS / US_ROUNDTRIP_CM != 0) && (uS / US_ROUNDTRIP_CM < 20)) {
digitalWrite(SENSOR_LED, HIGH);
Serial.println("Brown Jenkin within 20cm, ABORT ABORT!");
} else {
Serial.print("Ping: ");
Serial.print(uS / US_ROUNDTRIP_CM);
Serial.println("cm");
}

digitalWrite(SENSOR_LED, LOW);
delay(SENSOR_TIME);
}
[/sourcecode]

http://youtu.be/IsPIr8QnbK8

The Implementation






1 comment:

  1. [...] This is a continuation of my project here. You can get the code I implemented with the HC-SR04 at that post. [...]

    ReplyDelete