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); } 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); } Serial.print(distance); Serial.print("cm"); delay(100); }在这个代码中添一个舵机固定在15度到165度之间循环转动
时间: 2024-01-22 09:02:24 浏览: 57
好的,你可以将下面的代码加入到原来的代码中,以实现你的要求:
1. 在setup()函数中添加以下代码,用于初始化舵机:
```
#include <Servo.h>
Servo myservo;
myservo.attach(9);
```
2. 在loop()函数中,将以下代码添加到Serial.print("cm")之前,以实现舵机循环转动:
```
int angle = map(distance,2,400,15,165);
myservo.write(angle);
delay(10);
```
完整代码如下:
```
#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);
}
```
注意:这段代码中使用了舵机库,需要先在Arduino IDE中安装该库。
阅读全文