我想给我的机器人制造一些眼睛。它将使用伺服旋转超声波仪表HC-SR04,但当我添加代码驱动这个东西,伺服停止工作。为甚麽这样呢?我使用的是Arduino 1.5.6和Arduino Uno R3.
代码:
#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);
} 发布于 2014-10-21 16:14:04
我认为pulseIn()函数使用的计时器与Servo使用的计时器相同.您可以在回调中使用attachInterrupt()和substract time() - oldTime,然后将time()分配给oldTime
示例:http://arduino.cc/en/Reference/attachInterrupt
https://stackoverflow.com/questions/26490756
复制相似问题