keskiviikko 20. helmikuuta 2013

hc-sr04 ultrasonic sensor, with 4 legs + servo

I got new  hc-sr04 sensor with 4 legs. GND, ECHO, TRIG, VCC.

Connection setup: GND to GND of course, VCC goes +5V, echo to pin 13, trig to pin 12



This code prints distance to serial monitor:


#define trigPin 12
#define echoPin 13

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  int duration, distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}

Then i added a servo which moves if its between the wanted range:



Connection: servo to analog 0, PING to 12 and 13 as described in the actual code:


#define trigPin 12
#define echoPin 13
#include <Servo.h>
Servo servoMain; // Define our Servo

void setup() {
  Serial.begin (115200);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  servoMain.attach(A0); // servo on analog pin 0
}

void loop() {
servoMain.write(90);  // Turn Servo back to center position (90 degrees)

  int duration, distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
 
    Serial.print(distance);
    Serial.println(" cm");

  if (distance >=10 && distance <= 30){
     servoMain.write(135); // Turn Servo Right to 135 degrees
     delay(1000);          // Wait 1 second
     servoMain.write(25);  // Turn Servo Left to 45 degrees
  }
  else {
    servoMain.write(90);  // Turn Servo back to center position (90 degrees)
  }
  delay(500);
}




Then i wanted to test with the new battery case i got. I soldered jumper wires to the case so its easier to connect power to arduino.



 Just put plus (red wire) to VIM port and black one to GND = ground.  I am using arduino UNO which works with these voltages:
Input Voltage (recommended)7-12V
Input Voltage (limits)6-20V



Ei kommentteja:

Lähetä kommentti