本帖最後由 f660229 於 2017-12-25 20:02 編輯
我希望的功能,如標題4輪的自走車+4個伺服馬達0&90度的轉換。
現在arduino程式一輸入4個伺服就一直不斷的抖動,自走車的控制也不知道是否正確。
下面是我arduino的程式
#include <SoftwareSerial.h>
#include <Wire.h>
#include <Servo.h>
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;
SoftwareSerial BT(0,1);
const int leftMotorIn1 = 4;
const int leftMotorIn2 = 5;
const int rightMotorIn3 = 6;
const int rightMotorIn4 = 7;
const int leftMotorIn5 = 8;
const int leftMotorIn6 = 9;
const int rightMotorIn7 = 10;
const int rightMotorIn8 = 11;
char command;
void setup()
{
pinMode(leftMotorIn1, OUTPUT);
pinMode(leftMotorIn2, OUTPUT);
pinMode(rightMotorIn3, OUTPUT);
pinMode(rightMotorIn4, OUTPUT);
pinMode(leftMotorIn5, OUTPUT);
pinMode(leftMotorIn6, OUTPUT);
pinMode(rightMotorIn7, OUTPUT);
pinMode(rightMotorIn8, OUTPUT);
Serial.begin(38400);
BT.begin(38400);
servo1.attach(2);
servo2.attach(3);
servo3.attach(12);
servo4.attach(13);
servo1.write(0);
servo2.write(0);
servo3.write(0);
servo4.write(0);
}
void loop()
{
if(BT.available() > 0)
{
command = BT.read();
Serial.println(command);
switch (command) {
case 'A':
forward();
break;
case 'B':
backward();
break;
case 'C':
left();
break;
case 'D':
right();
break;
case 'S':
motorstop();
break;
case 'E':
servo1.write(90);
servo2.write(90);
servo3.write(90);
servo4.write(90);
break;
case 'F':
servo1.write(0);
servo2.write(0);
servo3.write(0);
servo4.write(0);
break;
}
}
}
void motorstop()
{
digitalWrite(leftMotorIn1, LOW);
digitalWrite(leftMotorIn2, LOW);
digitalWrite(rightMotorIn3, LOW);
digitalWrite(rightMotorIn4, LOW);
digitalWrite(leftMotorIn5, LOW);
digitalWrite(leftMotorIn6, LOW);
digitalWrite(rightMotorIn7, LOW);
digitalWrite(rightMotorIn8, LOW);
}
void forward()
{
digitalWrite(leftMotorIn1, HIGH);
digitalWrite(leftMotorIn2, LOW);
digitalWrite(rightMotorIn3, HIGH);
digitalWrite(rightMotorIn4, LOW);
digitalWrite(leftMotorIn5, HIGH);
digitalWrite(leftMotorIn6, LOW);
digitalWrite(rightMotorIn7, HIGH);
digitalWrite(rightMotorIn8, LOW);
}
void backward()
{
digitalWrite(leftMotorIn1, LOW);
digitalWrite(leftMotorIn2, HIGH);
digitalWrite(rightMotorIn3, LOW);
digitalWrite(rightMotorIn4, HIGH);
digitalWrite(leftMotorIn5, LOW);
digitalWrite(leftMotorIn6, HIGH);
digitalWrite(rightMotorIn7, LOW);
digitalWrite(rightMotorIn8, HIGH);
}
void right()
{
digitalWrite(leftMotorIn1, HIGH);
digitalWrite(leftMotorIn2, LOW);
digitalWrite(rightMotorIn3, LOW);
digitalWrite(rightMotorIn4, HIGH);
digitalWrite(leftMotorIn5, HIGH);
digitalWrite(leftMotorIn6, LOW);
digitalWrite(rightMotorIn7, LOW);
digitalWrite(rightMotorIn8, HIGH);
}
void left()
{
digitalWrite(leftMotorIn1, LOW);
digitalWrite(leftMotorIn2, HIGH);
digitalWrite(rightMotorIn3, HIGH);
digitalWrite(rightMotorIn4, LOW);
digitalWrite(leftMotorIn5, LOW);
digitalWrite(leftMotorIn6, HIGH);
digitalWrite(rightMotorIn7, HIGH);
digitalWrite(rightMotorIn8, LOW);
}
提一個額外的問題,為什麼RXT&TXD輸入跟輸出的時候要互換? |