我们这里使用的是L298N和UNO联合使用,实现小车的寻迹。
利用灰度传感器进行黑线的识别。
这里记录一下出版代码。
#include"AFMotor.h"
//define the grayscale sensor pins
#define LEFT_SENSOR A0
#define CENTER_LEFT_SENSOR A1
#define CENTER_RIGHT_SENSOR A2
#define RIGHT_SENSOR A3
//define the label of wheels
#define Front_Left 1
#define Front_Right 2
#define Back_Left 3
#define Back_Right 4
//initate four sensor objects which is used to detect the black lines
//number 1 to 4 are the label of the motor
AF_DCMotor motor1(Front_Left); // front-left wheel
AF_DCMotor motor2(Front_Right);
AF_DCMotor motor3(Back_Left);
AF_DCMotor motor4(Back_Right);
void setup() {
// put your setup code here, to run once:
motor1.setSpeed(255); // set the speed of the motor
motor2.setSpeed(255);
motor3.setSpeed(255);
motor4.setSpeed(255);
Serial.begin(9600); // initate serial communication and set the frequency at 9600 in order to print information on the screen
}
void loop() {
// put your main code here, to run repeatedly:
//read and save the values from the grayscale sensors
int leftValue = analogRead(LEFT_SENSOR);
int centerLeftValue = analogRead(CENTER_LEFT_SENSOR);
int centerRightValue = analogRead(CENTER_RIGHT_SENSOR);
int rightValue = analogRead(RIGHT_SENSOR);
//print the values in order to modify
Serial.print("Left: ");
Serial.print(leftValue);
Serial.print(" Center Left: ");
Serial.print(centerLeftValue);
Serial.print(" Center Right: ");
Serial.print(centerRightValue);
Serial.print(" Right: ");
Serial.println(rightValue);
if (centerLeftValue < 500 && centerRightValue < 500) {
// 中间传感器检测到黑线,前进
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
} else if (leftValue < 500) {
// 左传感器检测到黑线,左转
motor1.run(BACKWARD);
motor2.run(FORWARD);
motor3.run(FORWARD);
motor4.run(BACKWARD);
} else if (rightValue < 500) {
// 右传感器检测到黑线,右转
motor1.run(FORWARD);
motor2.run(BACKWARD);
motor3.run(BACKWARD);
motor4.run(FORWARD);
} else {
// 没有传感器检测到黑线,停止
motor1.run(RELEASE);
motor2.run(RELEASE);
motor3.run(RELEASE);
motor4.run(RELEASE);
}
}