arduino超声波避障小车代码
时间: 2023-09-10 20:04:51 浏览: 169
:基于Arduino单片机避障小车机器人.docx
以下是一个基本的Arduino超声波避障小车代码:
```
#include <NewPing.h>
#define TRIG_PIN 12
#define ECHO_PIN 11
#define MAX_DISTANCE 200
#define LEFT_MOTOR_PIN1 6
#define LEFT_MOTOR_PIN2 7
#define RIGHT_MOTOR_PIN1 8
#define RIGHT_MOTOR_PIN2 9
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LEFT_MOTOR_PIN1, OUTPUT);
pinMode(LEFT_MOTOR_PIN2, OUTPUT);
pinMode(RIGHT_MOTOR_PIN1, OUTPUT);
pinMode(RIGHT_MOTOR_PIN2, OUTPUT);
}
void goForward() {
digitalWrite(LEFT_MOTOR_PIN1, HIGH);
digitalWrite(LEFT_MOTOR_PIN2, LOW);
digitalWrite(RIGHT_MOTOR_PIN1, HIGH);
digitalWrite(RIGHT_MOTOR_PIN2, LOW);
}
void goBackward() {
digitalWrite(LEFT_MOTOR_PIN1, LOW);
digitalWrite(LEFT_MOTOR_PIN2, HIGH);
digitalWrite(RIGHT_MOTOR_PIN1, LOW);
digitalWrite(RIGHT_MOTOR_PIN2, HIGH);
}
void turnLeft() {
digitalWrite(LEFT_MOTOR_PIN1, LOW);
digitalWrite(LEFT_MOTOR_PIN2, HIGH);
digitalWrite(RIGHT_MOTOR_PIN1, HIGH);
digitalWrite(RIGHT_MOTOR_PIN2, LOW);
}
void turnRight() {
digitalWrite(LEFT_MOTOR_PIN1, HIGH);
digitalWrite(LEFT_MOTOR_PIN2, LOW);
digitalWrite(RIGHT_MOTOR_PIN1, LOW);
digitalWrite(RIGHT_MOTOR_PIN2, HIGH);
}
void stop() {
digitalWrite(LEFT_MOTOR_PIN1, LOW);
digitalWrite(LEFT_MOTOR_PIN2, LOW);
digitalWrite(RIGHT_MOTOR_PIN1, LOW);
digitalWrite(RIGHT_MOTOR_PIN2, LOW);
}
void loop() {
unsigned int distance = sonar.ping_cm();
if (distance <= 10) {
stop();
delay(500);
turnLeft();
delay(500);
}
else {
goForward();
}
}
```
这个代码使用了NewPing库来测量超声波距离,并根据距离来控制小车的行动。如果距离小于等于10厘米,则停止并向左转500毫秒,否则向前行驶。小车的行动通过设置电机的引脚状态来实现。
阅读全文