用五路红外传感器,L298N电机驱动,Arduino Uno主板。帮我写代码,列出接线表
时间: 2024-05-28 15:15:21 浏览: 93
L298 电机驱动芯片的接线图
5星 · 资源好评率100%
好的,您需要使用五路红外传感器和L298N电机驱动模块来控制Arduino Uno主板上的电机。
以下是接线表和代码:
接线表:
红外传感器:
VCC —> 5V
GND —> GND
OUT1 —> Digital Pin 2
OUT2 —> Digital Pin 3
OUT3 —> Digital Pin 4
OUT4 —> Digital Pin 5
OUT5 —> Digital Pin 6
L298N电机驱动模块:
ENA —> Digital Pin 9
IN1 —> Digital Pin 7
IN2 —> Digital Pin 8
IN3 —> Digital Pin 10
IN4 —> Digital Pin 11
ENB —> Digital Pin 12
+5V —> 5V
GND —> GND
电机:
电机A —> OUT1 和 OUT2
电机B —> OUT3 和 OUT4
代码:
// Red Infrared Sensor Inputs
int sensor1 = 2;
int sensor2 = 3;
int sensor3 = 4;
int sensor4 = 5;
int sensor5 = 6;
// Motor Control Inputs
int enA = 9;
int in1 = 7;
int in2 = 8;
int in3 = 10;
int in4 = 11;
int enB = 12;
// Motor Speeds
int leftSpeed = 200;
int rightSpeed = 200;
void setup() {
// Initialize motors
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
pinMode(enB, OUTPUT);
// Initialize sensors
pinMode(sensor1, INPUT);
pinMode(sensor2, INPUT);
pinMode(sensor3, INPUT);
pinMode(sensor4, INPUT);
pinMode(sensor5, INPUT);
}
void loop() {
// Read infrared sensors
int s1 = digitalRead(sensor1);
int s2 = digitalRead(sensor2);
int s3 = digitalRead(sensor3);
int s4 = digitalRead(sensor4);
int s5 = digitalRead(sensor5);
// Determine motor speeds
if (s1 == HIGH || s2 == HIGH) {
// Turn left
leftSpeed = -150;
rightSpeed = 200;
} else if (s4 == HIGH || s5 == HIGH) {
// Turn right
leftSpeed = 200;
rightSpeed = -150;
} else {
// Move forward
leftSpeed = 200;
rightSpeed = 200;
}
// Control motor speeds
analogWrite(enA, abs(leftSpeed));
analogWrite(enB, abs(rightSpeed));
digitalWrite(in1, leftSpeed > 0 ? HIGH : LOW);
digitalWrite(in2, leftSpeed > 0 ? LOW : HIGH);
digitalWrite(in3, rightSpeed > 0 ? HIGH : LOW);
digitalWrite(in4, rightSpeed > 0 ? LOW : HIGH);
}
请注意,本代码适用于控制具有当红外线传感器检测到障碍物时进行调整的小型机器人。因此,请根据您的整个电路进行必要的修改。
阅读全文