编程的整体思想是先判断黑线的位置,当中间传感器扫描到黑线时,小车位置正确,电机继续按原始速度行走;当左侧传感器扫描到黑线时,此时小车已经偏右,需要及时向左校正,左侧电机减速,右侧电机加速,完成左转;当右侧传感器扫描到黑线时,此时小车已经偏左,需要及时向右校正,左侧电机加速,右侧电机减速,完成右转;下面列出上述电路连接对应的程序:
static int initial_motor_speed=100;
const int IN_A1=6;
const int IN_A2=9;
const int IN_B1=10;
const int IN_B2=11;
const int sensor2=2;
const int sensor3=3;
const int sensor4=4;
void setup() {
pinMode(IN_A1,OUTPUT);
pinMode(IN_A2,OUTPUT);
pinMode(IN_B1,OUTPUT);
pinMode(IN_B2,OUTPUT);
pinMode(sensor2,INPUT);
pinMode(sensor3,INPUT);
pinMode(sensor4,INPUT);
}
void loop() {
char num2,num3,num4;
num2=digitalRead(sensor2);
num3=digitalRead(sensor3);
num4=digitalRead(sensor4);
if(num4==0){
analogWrite(IN_A1,150);
analogWrite(IN_A2,0);
analogWrite(IN_B1,50);
analogWrite(IN_B2,0);
}else if(num2==0){
analogWrite(IN_A1,50);
analogWrite(IN_A2,0);
analogWrite(IN_B1,150);
analogWrite(IN_B2,0);
}else{
analogWrite(IN_A1,100);
analogWrit