Hello
I am having a little issue with a code I have.
The idea is I'm controlling a motor via an ESC with an RC controller
the stop command works, the reverse command works, but the forward command only kinda works, the motor turns but will intermittently stop and start again.
if I remove the ( digitalWrite (RMotorDir, HIGH); ) from the second 'else if' the forward command works fine
#include <Servo.h>
#define RCPinFWD 2 //Right RC stick
#define RCPinSide 3 // Left RC stick
#define RMotorStop 4 //Right mortor stop contorll
#define RMotorDir 5 //Right mortor stop contorll
#define LMotorStop 6 //Left mortor stop contorll
#define LMotorDir 7 //Left mortor stop contorll
Servo RightMotor;
Servo LeftMotor;
volatile long StartTimeFWD = 0;
volatile long CurrentTimeFWD = 0;
volatile long PulsesFWD = 0;
int PulseWidthFWD = 0;
volatile long StartTimeSide = 0;
volatile long CurrentTimeSide = 0;
volatile long PulsesSide = 0;
int PulseWidthSide = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(RCPinFWD, INPUT_PULLUP);
pinMode(RCPinSide, INPUT_PULLUP);
pinMode(RMotorStop, OUTPUT);
pinMode(RMotorDir, OUTPUT);
pinMode(LMotorStop, OUTPUT);
pinMode(LMotorDir, OUTPUT);
attachInterrupt(digitalPinToInterrupt(RCPinFWD),PulseTimerFWD,CHANGE);
attachInterrupt(digitalPinToInterrupt(RCPinSide),PulseTimerSide,CHANGE);
RightMotor.attach(10);
LeftMotor.attach(11);
digitalWrite (RMotorStop, HIGH);
}
void loop() {
// put your main code here, to run repeatedly:
//only save pulse lengths that are less than 2000 microseconds
if (PulsesFWD < 2000){
PulseWidthFWD = PulsesFWD;
}
if (PulsesSide < 2000){
PulseWidthSide = PulsesSide;
}
Serial.print(PulseWidthFWD);
Serial.print(" ");
Serial.println(PulseWidthSide);
if ((PulseWidthFWD < 1540) && (PulseWidthFWD > 1480)){ //If the stick is centered stop
digitalWrite (RMotorStop, HIGH);
}
else if (PulseWidthFWD > 1540){ //if stick is up motor forward
digitalWrite (RMotorStop, LOW);
digitalWrite (RMotorDir, LOW);
PulseWidthFWD = map(PulseWidthFWD, 1540, 1900, 0, 180);
RightMotor.write(PulseWidthFWD);
}
else if (PulseWidthFWD < 1480){ //if stick is down motor backwards
digitalWrite (RMotorStop, LOW);
digitalWrite (RMotorDir, HIGH);
PulseWidthFWD = map(PulseWidthFWD, 1480, 1100, 0, 180);
RightMotor.write(PulseWidthFWD);
}
}
void PulseTimerFWD(){
CurrentTimeFWD = micros();
if (CurrentTimeFWD > StartTimeFWD){
PulsesFWD = CurrentTimeFWD - StartTimeFWD;
StartTimeFWD = CurrentTimeFWD;
}
}
void PulseTimerSide(){
CurrentTimeSide = micros();
if (CurrentTimeSide > StartTimeSide){
PulsesSide = CurrentTimeSide - StartTimeSide;
StartTimeSide = CurrentTimeSide;
}
}