You are here

rateira 'dixital', maqueta funcionameto

compoñentes:

  • servo
  • sensor ultrasons
  • arduino

#include <Servo.h>
Servo servo;

static const int minAngle = 90;
static const int maxAngle = 175;
int servoAngle;
int servoPos;
int servoPin = 9;

const int ledPin =  3;  

/* Define pins for HC-SR04 ultrasonic sensor */
#define echoPin A0 // Echo Pin = Analog Pin 0
#define trigPin A1 // Trigger Pin = Analog Pin 1
#define LEDPin 13 // Onboard LED
long duration; // Duration used to calculate distance
long distancia=0; // Calculated Distance
int HR_angle=0; // The angle in which the servo/sensor is pointing
int HR_dir=1; // Used to change the direction of the servo/sensor
int minDistancia=5;
int maxDistancia=10; //Maximum Sonar Range

/*--------------------SETUP()------------------------*/
void setup() {
 //Begin Serial communication using a 9600 baud rate
 Serial.begin (9600);
 
 servo.attach(servoPin);
 servo.write(minAngle);
 delay(500);
 servo.detach();
 
 //Setup the trigger and Echo pins of the HC-SR04 sensor
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 pinMode(ledPin, OUTPUT); // Use LED indicator (if required)
}

/*----------------------LOOP()--------------------------*/
void loop() {
 getDistance();
// delay(500);
}

/*--------------------getDistance() FUNCTION ---------------*/
void getDistance(){
 /* The following trigPin/echoPin cycle is used to determine the
 distance of the nearest object by bouncing soundwaves off of it. */
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);

 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10);
 
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 
 //Calculate the distance (in cm) based on the speed of sound.
 distancia = duration/58.2;
 
 //if (HR_dist >= maximumRange || HR_dist <= minimumRange){
  if (distancia <= minDistancia){
   digitalWrite(ledPin, HIGH);
   servo.attach(servoPin);
   servo.write(minAngle);
   delay(250);
   servo.detach();
 }
 //} else {
   
  if (distancia >= maxDistancia){
   digitalWrite(ledPin, LOW);
   servo.attach(servoPin);
   servo.write(maxAngle);
   delay(250);
   servo.detach();
 }
}
info: