perjantai 25. tammikuuta 2013

Arduino ping sensor


Me and Anders got a PING ultrasonic sensor. Our task was to find out what it does and how. Here is the sensor:


It sends ultrasonic sound from the other tube and then the other one is microphone which caches the sound. Then the actual code calculates how long it took for the sound to travel to the obstacle and back. Here is some basic code which sets the led in socket 13 on IF the distance is bigger than 10. If it's smaller than ten the led will turn off.

Connect PING signal to pin 7, GND to GND and power to +5v

#define fP 7 //Pin the ping sensor is connected to
void setup()
{
  pinMode(13, OUTPUT);     
}
void loop()
{
  if (ping() > 10) // set distance
  {
    digitalWrite(13, HIGH);   // set the LED on
  }
  else
  {
    digitalWrite(13, LOW);    // set the LED off
  }
}
int ping() //Get CM to obstacle in front of the sensor
{
  long duration;
  pinMode(fP, OUTPUT);
  digitalWrite(fP, LOW);
  delayMicroseconds(2);
  digitalWrite(fP, HIGH);
  delayMicroseconds(15);
  digitalWrite(fP, LOW);
  delayMicroseconds(20);
  pinMode(fP, INPUT);
  duration = pulseIn(fP, HIGH);
  return duration / 29.0 / 2.0;
}


Then we just added more leds and added distances when the led's should be active:



I forgot to shoot my own video, but my friend took one and here is how it works.



//#define fP 7 //Pin the ping sensor is connected to
const int pingPin = 7; //set ping to slot 7

void setup()
{
  pinMode(4, OUTPUT); //
  pinMode(5, OUTPUT); //set led to slot 4,5,6
  pinMode(6, OUTPUT); //
}

void loop()
{
  if (ping() > 2) //if ping distance is bigger than #
{
  digitalWrite(4, HIGH); //set the LED on
}
 else if(ping() > 6)
{
  digitalWrite(5, HIGH);
}
  else if(ping() > 10)
{
  digitalWrite(6, HIGH);
}
else
{
  digitalWrite(4, LOW); //
  digitalWrite(5, LOW); //set the LED off
  digitalWrite(6, LOW); //
}
}
int ping() //Get CM to obstacle in front of the sensor
{
long duration;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(15);
digitalWrite(pingPin, LOW);
delayMicroseconds(20);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
return duration / 29.0 / 2.0;
}

Ei kommentteja:

Lähetä kommentti