I am using an Arduino Mega and using the ServoInput library to read my RC receiver throttle. I take that input and map it to 0-255 then send it to my motor via pwm pin 9. The code works flawless as long as I comment out the analogWrite(PWM,mappedValue). If I uncomment the line it starts skipping reading values and I get some zeros which then makes the motor not turn smoothly. Here is my code.
#include <ServoInput.h>
byte PWM =9;
// Throttle Setup
const int ThrottleSignalPin = 2; // MUST be interrupt-capable!
const int ThrottlePulseMin = 900; // microseconds (us)
const int ThrottlePulseMax =1985; //calibrated values for min/max
ServoInputPin<ThrottleSignalPin> throttle(ThrottlePulseMin, ThrottlePulseMax);
void setup() {
Serial.begin(115200);
pinMode(PWM, OUTPUT);
analogWrite(PWM, 0);
}
void loop() {
int throttlePercent = throttle.map(0, 255); // remap to a percentage both forward and reverse
Serial.print("Throttle: ");Serial.println(throttlePercent);
//analogWrite(PWM, throttlePercent); //does not work right when I uncomment this line.
}
If I am not mistaken, I have moved the pwm to pin 11 which I believe uses timer2 and pin 2 uses timer 4. I still get skips in my throttle when sending pwm.
That made it a lot better but it is still doing it. It doesn't appear to be as often. I have changed from 50 all the way to 350. About 150 seems to be the best but it still happens.
I was not thinking correctly, of course it doesn't use timers. It does use a pin interrupt. I think there is some timing issue with the interrupt. It's possible that the servo library depends on interrupts not being disabled, maybe the code for analogWrite turns them off momentarily...
Can you modify the program to do an additional serial debug print, every time a PWM write is performed (atm, in the millis block)?
Also can you please repost the modified test code?
That is where I currently do the print statement. Here is the code:
#include <ServoInput.h>
byte PWM =11;
// Throttle Left Setup
const int ThrottleSignalPin = 2; // MUST be interrupt-capable!
const int ThrottlePulseMin = 900; // microseconds (us)
const int ThrottlePulseMax = 2000; // Ideal values for your servo can be found with the "Calibration" example
//
ServoInputPin<ThrottleSignalPin> throttle(ThrottlePulseMin, ThrottlePulseMax);
unsigned long tstamp;
void setup() {
Serial.begin(115200);
pinMode(PWM, OUTPUT);
analogWrite(PWM, 0);
}
void loop() {
if (millis() - tstamp >= 150) {
tstamp += 150;
int throttlePercent = throttle.map(0, 255); // remap to a percentage both forward and reverse
Serial.print("Throttle: ");Serial.println(throttlePercent);
analogWrite(PWM, throttlePercent);
}
}
I am using a KBBC-24 as a motor driver and that is what I feed the PWM signal. I have noticed that I can turn it off and the signal is correct. I turn on power to the kbbc board and the problem returns. The only wires that go from the board to the kbbc board is the pwm signal wire and a ground wire.