所以我有一个问题,当我用超声波传感器运行我的代码时,h桥与电机一起旋转,一个电机始终旋转,另一个电机每 6 秒旋转 2 秒,但我不知道为什么。有什么帮助吗?
这是代码:
int in1 = 2;
int in2 = 3;
int in3 = 4;
int in4 = 5;
int in5 = 6;
int in6 = 7;
int trig = 8;
int echol = 9;
int echor = 12;
int echof = 11;
long df, tf, dr, tr, dl, tl;
void setup() {
Serial.begin(9600);
}
void loop() {
pinMode (in1, OUTPUT);
pinMode (in2, OUTPUT);
pinMode (in3, OUTPUT);
pinMode (in4, OUTPUT);
pinMode (in5, OUTPUT);
pinMode (in6, OUTPUT);
pinMode (trig, OUTPUT);
pinMode (echol, INPUT);
pinMode (echor, INPUT);
pinMode (echof, INPUT);
forward();
digitalWrite (trig, HIGH);
delay (0.01);
tf = pulseIn (echof, HIGH);
digitalWrite (trig, LOW);
df = tf * 0.03156;
if (df < 1.5){
digitalWrite (trig, HIGH);
delay (0.01);
tr = pulseIn (echor, HIGH);
tl = pulseIn (echol, HIGH);
digitalWrite (trig, LOW);
dr = tr * 0.03156;
dl = tl * 0.03156;
if (dr > dl) {
right();
delay (5000);
forward();
}
else {
left();
delay (5000);
forward();
}
}
}
void forward(){
digitalWrite (in1, HIGH);
digitalWrite (in2, LOW);
digitalWrite (in3, HIGH);
digitalWrite (in4, LOW);
digitalWrite (in5, HIGH);
digitalWrite (in6, LOW);
}
void backward(){
digitalWrite (in1, LOW);
digitalWrite (in2, HIGH);
digitalWrite (in3, LOW);
digitalWrite (in4, HIGH);
digitalWrite (in5, LOW);
digitalWrite (in6, HIGH);
}
void left(){
digitalWrite (in1, LOW);
digitalWrite (in2, LOW);
digitalWrite (in3, HIGH);
digitalWrite (in4, LOW);
digitalWrite (in5, HIGH);
digitalWrite (in6, LOW);
}
void right(){
digitalWrite (in1, HIGH);
digitalWrite (in2, LOW);
digitalWrite (in3, LOW);
digitalWrite (in4, LOW);
digitalWrite (in5, HIGH);
digitalWrite (in6, LOW);
}