循迹小车arduino MEGA2560控制电机l258n六路循迹板代码
时间: 2023-12-20 12:29:56 浏览: 285
基于Arduino MEGA2560的智能物流小车
以下是循迹小车arduino MEGA2560控制电机l258n六路循迹板代码的示例:
```arduino
//定义引脚
int leftmotor1 = 22;
int leftmotor2 = 23;
int rightmotor1 = 24;
int rightmotor2 = 25;
int leftsensor1 = 2;
int leftsensor2 = 3;
int centersensor = 4;
int rightsensor2 = 5;
int rightsensor1 = 6;
void setup() {
//设置引脚模式
pinMode(leftmotor1, OUTPUT);
pinMode(leftmotor2, OUTPUT);
pinMode(rightmotor1, OUTPUT);
pinMode(rightmotor2, OUTPUT);
pinMode(leftsensor1, INPUT);
pinMode(leftsensor2, INPUT);
pinMode(centersensor, INPUT);
pinMode(rightsensor2, INPUT);
pinMode(rightsensor1, INPUT);
}
void loop() {
//读取传感器值
int left1 = digitalRead(leftsensor1);
int left2 = digitalRead(leftsensor2);
int center = digitalRead(centersensor);
int right2 = digitalRead(rightsensor2);
int right1 = digitalRead(rightsensor1);
//判断传感器值,控制电机
if (center == HIGH) {
digitalWrite(leftmotor1, HIGH);
digitalWrite(leftmotor2, LOW);
digitalWrite(rightmotor1, HIGH);
digitalWrite(rightmotor2, LOW);
} else if (left1 == HIGH && left2 == LOW) {
digitalWrite(leftmotor1, LOW);
digitalWrite(leftmotor2, HIGH);
digitalWrite(rightmotor1, HIGH);
digitalWrite(rightmotor2, LOW);
} else if (right1 == HIGH && right2 == LOW) {
digitalWrite(leftmotor1, HIGH);
digitalWrite(leftmotor2, LOW);
digitalWrite(rightmotor1, LOW);
digitalWrite(rightmotor2, HIGH);
} else if (left2 == HIGH && right2 == HIGH) {
digitalWrite(leftmotor1, LOW);
digitalWrite(leftmotor2, HIGH);
digitalWrite(rightmotor1, LOW);
digitalWrite(rightmotor2, HIGH);
} else if (left1 == LOW && right1 == LOW) {
digitalWrite(leftmotor1, LOW);
digitalWrite(leftmotor2, LOW);
digitalWrite(rightmotor1, LOW);
digitalWrite(rightmotor2, LOW);
}
}
```
阅读全文