我的自走車功能是有減速馬達&伺服馬達的組合 減速馬達用來驅動輪子的 伺服馬達有另外的功能 減速馬達&伺服馬達程式分開用的話動作正常 但何在一起後動作雖然一樣 但會有不定時的延遲 請問要怎麼解決???(下面是減速馬達+伺服馬達的程式)
#include<SoftwareSerial.h>
#include <Servo.h>
#include <Wire.h>
Servo UDservo;
Servo LRservo;
SoftwareSerial BT (11,12);
char command;
float ang = 90;
const int leftMotorIn1 = 4;
const int leftMotorIn2 = 5;
const int rightMotorIn3 = 6;
const int rightMotorIn4 = 7;
bool isForward = true;
void setup()
{
pinMode(leftMotorIn1, OUTPUT);
pinMode(leftMotorIn2, OUTPUT);
pinMode(rightMotorIn3, OUTPUT);
pinMode(rightMotorIn4, OUTPUT);
BT.begin(38400);
Serial.begin(38400);
UDservo.attach(2);
LRservo.attach(3);
UDservo.write(90);
LRservo.write(90);
}
void loop()
{
if (BT.available() > 0)
{
command = BT.read();
Serial.println(command);
switch (command) {
case'A':
ang = ang + 3;
if (ang > 180) ang = 180;
UDservo.write(ang);
delay(40);
break;
case 'B':
ang = ang -3;
if (ang < 0) ang = 0;
UDservo.write(ang);
delay(40);
break;
case'C':
ang = ang -3;
if (ang < 0) ang = 0;
LRservo.write(ang);
delay(40);
break;
case'D':
ang = ang + 3;
if (ang > 180) ang = 180;
LRservo.write(ang);
delay(40);
break;
}
}
int inSize;
char input;
if( (inSize = (BT.available())) > 0) { //讀取藍牙訊息
Serial.print("size = ");
Serial.println(inSize);
Serial.print("Input = ");
Serial.println(input=(char)BT.read());
if( input == 'E' ) {
forward();
isForward = true;
}
if( input == 'F' ) {
backward();
isForward = false;
}
if( input == 'H' ) {
left();
}
if( input == 'G' ) {
right();
}
if( input == 'I' ) {
motorstop();
}
}
}
void motorstop()
{
digitalWrite(leftMotorIn1, LOW);
digitalWrite(leftMotorIn2, LOW);
digitalWrite(rightMotorIn3, LOW);
digitalWrite(rightMotorIn4, LOW);
}
void forward()
{
digitalWrite(leftMotorIn1, HIGH);
digitalWrite(leftMotorIn2, LOW);
digitalWrite(rightMotorIn3, HIGH);
digitalWrite(rightMotorIn4, LOW);
}
void backward()
{
digitalWrite(leftMotorIn1, LOW);
digitalWrite(leftMotorIn2, HIGH);
digitalWrite(rightMotorIn3, LOW);
digitalWrite(rightMotorIn4, HIGH);
}
void left()
{
digitalWrite(leftMotorIn1, HIGH);
digitalWrite(leftMotorIn2, LOW);
digitalWrite(rightMotorIn3, LOW);
digitalWrite(rightMotorIn4, LOW);
}
void right()
{
digitalWrite(leftMotorIn1, LOW);
digitalWrite(leftMotorIn2, LOW);
digitalWrite(rightMotorIn3, HIGH);
digitalWrite(rightMotorIn4, LOW);
} |