Sunday, April 17, 2016

Developing Code for Brake


This is the program that we have been working on to control the brake using the servo initially via an Arduino Uno.

   #include <Servo.h>
    const int trigPin = 9;
    const int echoPin = 10;
    Servo myservo;
    int pos = 0;
    // defines variables
    long duration;
    long distance;
    void setup() {
    pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
    pinMode(echoPin, INPUT); // Sets the echoPin as an Input
    Serial.begin(9600); // Starts the serial communication
    myservo.attach (8);

  }
    void loop() {
   
    // Clears the trigPin
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    // Sets the trigPin on HIGH state for 10 micro seconds
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    // Reads the echoPin, returns the sound wave travel time in microseconds
    duration = pulseIn(echoPin, HIGH);
    // Calculating the distance
    distance= duration*0.034/2;
    // Prints the distance on the Serial Monitor
    Serial.print("Distance: ");
    Serial.println(distance);



  int am = 7;
  if (am < distance){

    for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
       delay(15);                    // waits 15ms for the servo to reach the position
  }
  }

  else {
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {                              
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                    // waits 15ms for the servo to reach the position
  }
  }
    }

No comments:

Post a Comment