Wednesday, November 13, 2013

DapsBot beta code.

#include <Servo.h> 

const int buttonPin = 2;     // the number of the pushbutton pin
const int pingPin = 7;
int buttonState = 0;         // variable for reading the pushbutton status
Servo myservo;  // create servo object to control a servo 

void setup() {
  
  Serial.begin(9600); // initialize serial communication:
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object 
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop()
{
  // establish variables for duration of the ping, 
  // and the distance result in inches and centimeters:
  long duration, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);
  buttonState = digitalRead(buttonPin);

  // convert the time into a distance
  cm = microsecondsToCentimeters(duration);
  

  Serial.print(cm);
  Serial.print("cm");
  
  delay(100);
  if( cm < 10){
      myservo.write(180);                  // sets the servo position according to the scaled value 
      while( buttonState == HIGH){
      }
      myservo.write(0);
  }
  
}


long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}


Link to The Github gist-

https://gist.github.com/teamteamname/7472152

No comments:

Post a Comment