在下载到开发板之前要选择好板和端口,具体参见:
代码
int Left_motor_go=8;
int Left_motor_back=9;
int Right_motor_go=10;
int Right_motor_back=11;
int key=A2;
int beep=A3;
const int SensorRight = 3;
const int SensorLeft = 4;
int SL;
int SR;
void setup()
{
pinMode(Left_motor_go,OUTPUT);
pinMode(Left_motor_back,OUTPUT);
pinMode(Right_motor_go,OUTPUT);
pinMode(Right_motor_back,OUTPUT);
pinMode(key,INPUT);
pinMode(beep,OUTPUT);
pinMode(SensorRight, INPUT);
pinMode(SensorLeft, INPUT);
}
void run()
{
digitalWrite(Right_motor_go,HIGH);
digitalWrite(Right_motor_back,LOW);
analogWrite(Right_motor_go,60);
analogWrite(Right_motor_back,0);
digitalWrite(Left_motor_go,LOW);
digitalWrite(Left_motor_back,HIGH);
analogWrite(Left_motor_go,0);
analogWrite(Left_motor_back,60);
}
void brake()
{
digitalWrite(Right_motor_go,LOW);
digitalWrite(Right_motor_back,LOW);
digitalWrite(Left_motor_go,LOW);
digitalWrite(Left_motor_back,LOW);
}
void left()
{
digitalWrite(Right_motor_go,HIGH);
digitalWrite(Right_motor_back,LOW);
analogWrite(Right_motor_go,60);
analogWrite(Right_motor_back,0);
digitalWrite(Left_motor_go,LOW);
digitalWrite(Left_motor_back,LOW);
analogWrite(Left_motor_go,0);
analogWrite(Left_motor_back,0);
}
void spin_left()
{
digitalWrite(Right_motor_go,HIGH);
digitalWrite(Right_motor_back,LOW);
analogWrite(Right_motor_go,60);
analogWrite(Right_motor_back,0);
digitalWrite(Left_motor_go,HIGH);
digitalWrite(Left_motor_back,LOW);
analogWrite(Left_motor_go,30);
analogWrite(Left_motor_back,0);
}
void right()
{
digitalWrite(Right_motor_go,LOW);
digitalWrite(Right_motor_back,LOW);
analogWrite(Right_motor_go,0);
analogWrite(Right_motor_back,0);
digitalWrite(Left_motor_go,LOW);
digitalWrite(Left_motor_back,HIGH);
analogWrite(Left_motor_go,0);
analogWrite(Left_motor_back,60);
}
void spin_right()
{
digitalWrite(Right_motor_go,LOW);
digitalWrite(Right_motor_back,HIGH);
analogWrite(Right_motor_go,0);
analogWrite(Right_motor_back,30);
digitalWrite(Left_motor_go,LOW);
digitalWrite(Left_motor_back,HIGH);
analogWrite(Left_motor_go,0);
analogWrite(Left_motor_back,60);
}
void back(int time)
{
digitalWrite(Right_motor_go,LOW);
digitalWrite(Right_motor_back,HIGH);
analogWrite(Right_motor_go,0);
analogWrite(Right_motor_back,60);
digitalWrite(Left_motor_go,HIGH);
digitalWrite(Left_motor_back,LOW);
analogWrite(Left_motor_go,60);
analogWrite(Left_motor_back,0);
delay(time * 100);
}
void keysacn()
{
int val;
val=digitalRead(key);
while(!digitalRead(key))
{
val=digitalRead(key);
}
while(digitalRead(key))
{
delay(10);
val=digitalRead(key);
if(val==HIGH)
{
digitalWrite(beep,HIGH);
while(!digitalRead(key))
digitalWrite(beep,LOW);
}
else
digitalWrite(beep,LOW);
}
}
void loop()
{
keysacn();
while(1)
{
SR = digitalRead(SensorRight);
SL = digitalRead(SensorLeft);
if (SL == LOW&&SR==LOW)
run();
else if (SL == HIGH & SR == LOW)
spin_left();
else if (SR == HIGH & SL == LOW)
spin_right();
else
brake();
}
}