Hey guys, I'm new to the forum and to Arduino.
I have cobbled to gethe r this sketch. The idea is to have to ultrasonic sensors pointing in different directions both driving a servo. One driving the servo to one side the other sensor driving the servo to the other side. When both sensors are in range the servo will be driven to the middle.
The problem I'm having is I can only get the left sensor to work. When the right servo doesn't seem to be putting out a reading. It prints 0 to the serial port.
Please help.
Here is the code I'm using.
]//* This sketch is trying to read from to HC-SR04 sensors and drive a servo . One sensor drives
//the servo from0-80 deg the other from 100-10 deg.
#include<Servo.h>
Servo myservo;
#define trigPin 13
#define echoPin 12
#define echoPinr 7 //defining pins
void setup()
{
myservo.attach(9);
Serial.begin (9600);
pinMode (trigPin, OUTPUT);
pinMode (echoPin, INPUT);
pinMode (echoPinr, INPUT);
}
void loop()
{
int val; // declared the int "val"
int valr; // declared the int "valr"
int duration, distance; // declared the int "duration and distance"
int durationr, distancer; // declared the int "durationr and distancer"
digitalWrite(trigPin, HIGH); // turn on signal to ultrasonic sensor
delay(20);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
val = map(distance, 10, 50, 80, 0); // Getting the value from the sensor
durationr = pulseIn(echoPinr, HIGH);
distancer = (durationr/2) / 29.1;
valr = map(distancer, 10, 50, 100, 180);
if (val <10 >100 && valr <10 >100) //If both sensors in range servo goes to middle
myservo.write (90);
else if (val >10 <100) //If this sensor in range, write val to servo
myservo.write(val);
else if (valr >10 <100) //If this sensor in range, write valr to servo
myservo.write(valr);
else myservo.write(90); //if both sensors out of range then servo write to pos 90
Serial.print("Left" );
Serial.print(distance); //Prints the distance of the left sensor
Serial.print("cm");
Serial.println();
//delay(100);
Serial.print("Right" );
Serial.print(distancer); //Prints the distance of the right sensor
Serial.print("cm");
Serial.println();
//delay(100);
}