#include <Servo.h>Servo myservo;const int trig = 11; const int echo = 10; const int led = 3; void setup() { pinMode(trig, OUTPUT); pinMode(led, OUTPUT); pinMode(echo, INPUT); Serial.begin(9600); myservo.attach(9); } void loop() { digitalWrite(trig, LOW); delayMicroseconds(2); digitalWrite(trig,HIGH); delayMicroseconds(10); digitalWrite(trig, LOW); long duration = pulseIn(echo,HIGH); int distance = duration/58; if (distance >= 2 && distance <=400){ analogWrite(led,map(distance,2,400,255,0)); } else if(distance < 2) { analogWrite(led,255); } else{ analogWrite(led,0); } int angle = map(distance,2,400,15,165); myservo.write(angle); delay(10); Serial.print(distance); Serial.print("cm"); delay(100); }如何让舵机自由在15度和165度之间转动不受distance的干涉
时间: 2024-01-22 15:02:29 浏览: 61
不使用Servo.h的舵机驱动
要让舵机自由在15度和165度之间转动不受距离(distance)的干涉,可以将舵机的控制语句放在距离判断语句之前,这样无论距离是多少,都不会影响舵机的转动。以下是修改后的代码:
```
#include <Servo.h>
Servo myservo;
const int trig = 11;
const int echo = 10;
const int led = 3;
void setup() {
pinMode(trig, OUTPUT);
pinMode(led, OUTPUT);
pinMode(echo, INPUT);
Serial.begin(9600);
myservo.attach(9);
}
void loop() {
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig,HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
long duration = pulseIn(echo,HIGH);
int distance = duration/58;
int angle = map(distance,2,400,15,165);
myservo.write(angle);
delay(10);
if (distance >= 2 && distance <=400){
analogWrite(led,map(distance,2,400,255,0));
}
else if(distance < 2) {
analogWrite(led,255);
}
else{
analogWrite(led,0);
}
Serial.print(distance);
Serial.print("cm");
delay(100);
}
```
这样就可以实现距离检测和舵机转动的功能,而且舵机的转动不受距离的干涉。
阅读全文