Reputation: 513
I'm trying to create somekind of eyes for my robot. It will use a servo for rotation Ultrasonic Meter HC-SR04, but when I add code to drive this thing, servo stops working. Why is so? I'm using Arduino 1.5.6 and Arduino Uno R3.
Code:
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 90; // variable to store the servo position
int x = 0;
int y = 0;
int hcsr04[4] = {13,12,11,10};
float echoTime = 0;
float distance = 0;
void setup()
{
myservo.attach(3); // attaches the servo on pin 9 to the servo object
Serial.begin(9600);
myservo.write(pos);
for(int i = 0; i < 4; i++)
{
pinMode(hcsr04[i], OUTPUT);
}
pinMode(hcsr04[1], INPUT);
}
void loop()
{
x = analogRead(A0);
y = analogRead(A1);
if(y < 100)
{
pos += 1;
if(pos >= 175)
{
pos -= 10;
}
myservo.write(pos);
delay(10);
}
if(y > 900)
{
pos -= 1;
if(pos <= 5)
{
pos += 10;
}
myservo.write(pos);
delay(10);
}
digitalWrite(hcsr04[0], LOW);
delayMicroseconds(2);
digitalWrite(hcsr04[0], HIGH );
delayMicroseconds(10);
digitalWrite(hcsr04[0], LOW);
echoTime = pulseIn(hcsr04[1], HIGH);
distance = echoTime / 58;
Serial.println(pos);
}
Upvotes: 0
Views: 238
Reputation: 58
I think pulseIn() function uses the same timer that Servo is using... You could use attachInterrupt() and substract time() - oldTime in callback, then assign time() to oldTime
Example: http://arduino.cc/en/Reference/attachInterrupt
Upvotes: 1