所以我有一个问题,当我用超声波传感器运行我的代码,并且用电机桥接时,一个电机一直旋转,另一个电极每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);
}
答案 0 :(得分:0)
不确定所有错误,但将long
乘以tl * 0.03156并将值存储在long
中可能不会达到您的意图。您应该使用浮点值来包含这种计算的结果。
答案 1 :(得分:0)
首先,您应该在Setup()中移动引脚设置,无需在每个循环上重新初始化引脚i / o设置。
void Setup()
{
Serial.begin(9600);
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);
}
根据我对H-Bridge模块的了解,它们通常每个电机有3个输入,其中一次只能打开一个。我找不到与你的代码有关的任何关联....这是一个约束,所以你应该围绕它组织你的代码。它会使读取和调试更容易。 Arduino上没有调试器,因此组织代码确实有很大帮助。如果您需要更多帮助,其他人一定要更容易理解您的代码所做的事情。
void MotorA(int dir)
{
// dir = 0 = STOP, +1 = Forward, -1 = Reverse
digitalWrite(in1, dir > 0);
digitalWrite(in2, dir == 0); // You gave no details on the module
digitalWrite(in3, dir < 0); // you have. the actual logic may differ...
}
void MotorB(int dir)
{
// dir = 0 = STOP, +1 = Forward, -1 = Reverse
digitalWrite(in4, dir > 0);
digitalWrite(in5, dir == 0);
digitalWrite(in6, dir < 0);
}
void Stop()
{
MotorA(0);
MotorB(0);
}
void Forward()
{
MotorA(+1);
MotorB(+1);
}
void Reverse()
{
MotorA(-1);
MotorB(-1);
}
void Left()
{
MotorA(+1);
MotorB(-1);
}
void Right()
{
MotorA(-1);
MotorB(+1);
}
我是否还建议您从一个更简单的循环开始,直到您的电机运行?一次添加一个功能。这将有助于您最终更快地完成项目并准备好。
void Loop()
{
Forward()
delay(5000);
Stop()
delay(1000);
Reverse();
delay(1000);
// ---
}