小车遥控器

mb66c7f6a9ce3dc
发布于 2024-8-23 13:52
浏览
0收藏

#include <SoftwareSerial.h> // 引入串行通讯库

// 定义小车的两个电机
const int motorLeftA = 9;
const int motorLeftB = 10;
const int motorRightA = 5;
const int motorRightB = 6;

SoftwareSerial serial(7, 8); // 创建软件串口,连接到电脑的某个端口
void setup() {
// put your setup code here, to run once:

Serial.begin(9600); // 初始化串口通信
pinMode(motorLeftA, OUTPUT);
pinMode(motorLeftB, OUTPUT);
pinMode(motorRightA, OUTPUT);
pinMode(motorRightB, OUTPUT);

serial.begin(9600); // 开启串口通信

}
粗体
void loop() {
char command; // 接收命令
if (serial.available()) { // 如果有数据接收
command = serial.read(); // 读取字符
switch(command) { // 根据接收到的命令调整小车运动
case ‘F’: // 前进
digitalWrite(motorLeftA, HIGH);
digitalWrite(motorLeftB, LOW);
digitalWrite(motorRightA, HIGH);
digitalWrite(motorRightB, LOW);
break;
case ‘B’: // 后退
digitalWrite(motorLeftA, LOW);
digitalWrite(motorLeftB, HIGH);
digitalWrite(motorRightA, LOW);
digitalWrite(motorRightB, HIGH);
break;// 其他方向(左转、右转、停止)类似
case ‘e’: // 向左
digitalWrite(motorLeftA, LOW);
digitalWrite(motorLeftB, HIGH);
digitalWrite(motorRightA, LOW);
digitalWrite(motorRightB, HIGH);
break;// 其他方向(左转、右转、停止)类似
case ‘d’: // 向右
digitalWrite(motorLeftA, LOW);
digitalWrite(motorLeftB, HIGH);
digitalWrite(motorRightA, LOW);
digitalWrite(motorRightB, HIGH);
break;// 其他方向(左转、右转、停止)类似

    }
}

}

收藏
回复
举报
回复
    相关推荐