我想在计数器达到e,g num = 3(HIGH)之后停止直流电机,如下图所示:
白线厚3厘米,黑框30厘米平方!
两个红外传感器,int rightSens=30
;并且int leftSens=32;
正在工作并且在感应黑色表面时给出1
,在任何其他表面上给出0
,即白色且没有任何东西。
我希望机器人能像我的循环一样计算,3个LOW计数白色或2个HIGH计数黑色,然后做一些事情,例如停止,如while循环所示。
有些东西肯定是错的,似乎没有计算,因为它在通过3个盒子或3个白线后没有停止。任何帮助非常感谢!
int pwm=2; //initializing pin 2 as pwm
int leftMotorin_1=22;//right
int leftMotorin_2=24;
int pwm2=3;
int rightMotorin_3=26;
int rightMotorin_4=28;
//sensor
int rightSens=30;
int leftSens=32;
int rightSensState;
int leftSensState;
//Variables for counting lines
int previousState=0;
int currentState=0;
void setup ()
{
pinMode(pwm,OUTPUT); // set pwm pin as output
pinMode(leftMotorin_1,OUTPUT); //logic pins are also set as output
pinMode(leftMotorin_2,OUTPUT);
pinMode(pwm2,OUTPUT); // set pwm pin as output
pinMode(rightMotorin_3,OUTPUT); //logic pins are also set as output
pinMode(rightMotorin_4,OUTPUT);
//pinMode(obSens,INPUT);
pinMode(rightSens,INPUT);
pinMode(leftSens,INPUT);
}
void readSensors()
{
rightSensState = digitalRead(rightSens);
leftSensState = digitalRead(leftSens);
}
void moveForward()
{
digitalWrite(leftMotorin_1,HIGH);
digitalWrite(leftMotorin_2,LOW);
analogWrite(pwm,150);
digitalWrite(rightMotorin_3,HIGH);
digitalWrite(rightMotorin_4,LOW);
analogWrite(pwm2,150);
}
void stopWheels()
{
//For brake
digitalWrite(leftMotorin_1,LOW);
digitalWrite(leftMotorin_2,LOW);
digitalWrite(rightMotorin_3,LOW);
digitalWrite(rightMotorin_4,LOW);
}
void loop()
{
int count=0;
int num=3;
moveForward();
readSensors();
(currentState=(leftSensState && rightSensState));
if (currentState != previousState );
{
if (currentState==HIGH)
count++;
previousState=currentState;
}
while (count!=num) {
moveForward();
readSensors();
(currentState=(leftSensState && rightSensState));
if (currentState != previousState );
{
if (currentState==HIGH)
count+=1;
previousState=currentState;
}
if (counter == num)
{
stopWheels();
delay(20);
break;
}
}
}