arduino智能循迹小车代码(三个循迹模块)
#include <Servo.h>
int leftMotor1 = 3;
int leftMotor2 = 5;
int rightMotor1 = 6;
int rightMotor2 = 11;
int sum=0;
void setup() {
Serial.begin(9600);
pinMode(leftMotor1, OUTPUT);
pinMode(leftMotor2, OUTPUT);
pinMode(rightMotor1, OUTPUT);
pinMode(rightMotor2, OUTPUT);
pinMode(A0, INPUT);
pinMode(A1, INPUT);
pinMode(A2, INPUT);
}
void loop() {
tracing();
}
void tracing()
{
int data[4];
data[0]=analogRead(A0);
data[1]=analogRead(A1);
data[2]=analogRead(A2);
if(data[0]<210&&data[1]>500&&data[2]<210)//向前走
{
analogWrite(3,100);
analogWrite(5,0);
analogWrite(6,100);
analogWrite(11,0);
}
if(data[0]>500 &&data[1]<210 && data[2]<210) // 小车偏左
{
analogWrite(3,0);
analogWrite(5,0);
analogWrite(6,120);
analogWrite(11,0);
}
if(data[0]>500&&data[1]>500&&data[2]<210) //小车偏大左
{
analogWrite(3,0);
analogWrite(5,120);
analogWrite(6,120);
analogWrite(11,0);
}
if(data[0]<210&&(data[1]-30)<210&&data[2]>500) //小车偏右
{
analogWrite(3,120);
analogWrite(5,0);
analogWrite(6,0);
analogWrite(11,0);
}
if(data[0]<210&&data[1]>500&&data[2]>500) //小车偏大右
{
analogWrite(3,120);
analogWrite(5,0);
analogWrite(6,0);
analogWrite(11,120);
}
if(data[0]>500&&data[1]>500&&data[2]>500) //左右都检测到黑线是停止
{
analogWrite(3,0);
analogWrite(5,0);
analogWrite(6,0);
analogWrite(11,0);
}
Serial.print(data[0]);
Serial.print("---");
Serial.print(data[1]-30);
Serial.print("---");
Serial.print(data[2]);
Serial.print("---");
Serial.println(data[3]);
}