Problem using both Encoder Gear Motor and VILROS SG90 servo motor at same time

Hi! First time forum user, I’m hoping someone can help me out :slight_smile: This is a rather complex issue and I was not really able to simplify my sketch, so I’ve attached the entire file. I can offer simplification of any code if it is unclear, as I reference it throughout the post.

So I have an encoder motor (I could not find a spec sheet online but here is a link to the product) which is communicating pin interrupts with pins 2 and 3 on a SparkFun MIDI Shield connected to an Arduino Uno, and is receiving analog power from an H-Bridge connected to pins 10 and 11. Using the H-Bridge, the encoder is able to change rotation direction pretty easily. The point of this project is to write an Arduino sketch that will allow an encoder motor and a servo motor to both be controlled by MIDI commands. Alone, both motors work fine – the encoder motor can easily change direction and speed (Control Case 83 and 85 in the case structure), and I have complete control over the angle of the servo motor (case 89).

The problem arises when I combine the 2 codes. When I add servo commands into my preexisting encoder sketch (these are denoted by //SERVO in the attached sketch), and connect both motors (the Servo is connected to pin 5), the sketch works fine at first. I can change the speed of the encoder motor while also changing the angle of the servo motor. When I give the encoder the MIDI command to switch directions, the entire code stops. Both motors stop turning, and are unresponsive to any other commands I give them.

I detached the servo motor and kept the code the same, just driving the encoder, to see if the issue was with the hardware. The same error occurred.

My gut is telling me that it is some sort of software issue or somehow the pins used are interfering with each other, but I doubt it, and neither explanation explains to me why it works at first until the direction changes.

I have been fiddling with this problem for a couple days now, and would love any help that can be provided.

Thanks!

ArduinoPost_7_24_2018.ino (5.65 KB)

The servo library disables PWM (analogWrite) on pins 9 & 10.

I suspect the problem is that the Servo library and your TimerOne library are both trying to use the same HardwareTimer.

Try the servoTimer2 library

...R

Yup, its a common issue - the Servo library takes over timer1 the first time a servo call is made,
so that its PWM pins are no longer available for PWM.

Thank you! This makes a lot of sense.

Robin2, what does the servoTimer2 library do? Does it replace both the Servo and Timer1 Libraries? Or is it used in conjunction with them?

ServoTimer2 is to replace (only) the Servo library.

So I imported the ServoTimer2 library, but now the encoder motor is not turning at all

Nevermind -- I switched the encoder pins to 9 and 10 instead of 10 and 11 and it works!

Thank you!!