基于uno实现四驱寻迹小车

我们这里使用的是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);
  }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值