unsigned char PWM = 255;
int incomingByte = 0;
int pinI1=8;//定义I1接口
int pinI2=9;//定义I2接口
int speedpin=10;//定义EA(PWM调速)接口
int pinI3=4;//定义I3接口
int pinI4=5;//定义I4接口
int speedpin1=6;//定义EB(PWM调速)接口
int IRM=3;//定义中间避障传感器接口
void setup()
{
pinMode(pinI1,OUTPUT);
pinMode(pinI2,OUTPUT);
pinMode(pinI3,OUTPUT);
pinMode(pinI4,OUTPUT);
analogWrite(speedpin, PWM);
analogWrite(speedpin1, PWM);
pinMode(IRM,INPUT);
Serial.begin(9600);
}
void loop()
{
digitalWrite(pinI1,HIGH);
digitalWrite(pinI2,LOW);
digitalWrite(pinI3,HIGH);
digitalWrite(pinI4,LOW);
int m=digitalRead(IRM);
if(m==HIGH)
{
advance(120);
Serial.println("qianjin");
}
else
{
back(300);
Serial.println("houtui");
delay(1000);
left(100);
Serial.println("left");
delay(1000);
}
}
void advance(int a)//前进
{
analogWrite(speedpin,a);//输入模拟值进行设定速度
analogWrite(speedpin1,a);
digitalWrite(pinI4,LOW);//使直流电机(右)逆时针转
digitalWrite(pinI3,HIGH);
digitalWrite(pinI1,LOW);//使直流电机(左)顺时针转
digitalWrite(pinI2,HIGH);
}
void right(int b)//右转
{
analogWrite(speedpin,b);//输入模拟值进行设定速度
analogWrite(speedpin1,b);
digitalWrite(pinI4,HIGH);//使直流电机(右)顺时针转
digitalWrite(pinI3,LOW);
digitalWrite(pinI1,LOW);//使直流电机(左)顺时针转
digitalWrite(pinI2,HIGH);
}
void left(int c)//左转
{
analogWrite(speedpin,c);//输入模拟值进行设定速度
analogWrite(speedpin1,c);
digitalWrite(pinI4,LOW);//使直流电机(右)逆时针转
digitalWrite(pinI3,HIGH);
digitalWrite(pinI1,HIGH);//使直流电机(左)逆时针转
digitalWrite(pinI2,LOW);
}
void stop()//停止
{
digitalWrite(pinI4,HIGH);//使直流电机(右)制动
digitalWrite(pinI3,HIGH);
digitalWrite(pinI1,HIGH);//使直流电机(左)制动
digitalWrite(pinI2,HIGH);
}
void back(int d)//后退
{
analogWrite(speedpin,d);//输入模拟值进行设定速度
analogWrite(speedpin1,d);
digitalWrite(pinI4,HIGH);//使直流电机(右)顺时针转
digitalWrite(pinI3,LOW);
digitalWrite(pinI1,HIGH);//使直流电机(左)逆时针转
digitalWrite(pinI2,LOW);
}