Motor speed control doesn't work for 2 motors at the same time

Hi everyone.

I'm trying to develop a self-balacing robot on arduino 101.

I started making a basic control based on angle, without caring about motor response to pwm.

Then I realized I was better off making a speed control with the encoders that I'm using. I made a model on matlab for each motor and calibrated a PID for each.

To this point, if i run the code with only one of the motors at a time, it works great and it compensates for extra load to keep the RPM the same via incrementing the PWM output, but when I run both of the motors at the same time, at a set speed, it seems to crash after 2-3 seconds, and I'm going crazy about debugging this.

Would appriciate help on debugging this.

Some of the commenting is on spanish, but i think the code its pretty understandable.

sketch_sep21a.ino (7.06 KB)

What motors? What drivers? Maybe two motors at once is overloading your power supply.

#define pi 3.14159265358979

I have a sneaking suspicion that it would work just as well with 3.142

Floating point maths is very slowwww on an Arduino. I wonder if it has the capacity to do two lots of PID calculations fast enough. If you convert the code to use integers and avoid division unless it is absolutely essential it will probably only take one tenth of the time.

...R

MorganS:
What motors? What drivers? Maybe two motors at once is overloading your power supply.

I'm using 2 12v chinese motors with a L298N driver.

I don't think this is the case since it works totally fine without the speed control.

My personal thought process, maybe its the encoders interrupts, but it doesn't seem to be, because if I set one of the motors call to the PWM function to 0 and spin the stopped motor by hand it doesn't crash, so its shouldn't be the encoder interrupt or the speed calculation.

How to do direct port reading/writing as alternative to digitalRead/digitalWrite on arduino 101?

what other functions i'm using are slow?