I have been working with arduino for a while now and this is the first time I'm encountering such an issue. Before coming to the issue, I'll briefly explain what all I have done.
The project is to make a simple autonomous robot. I'm using the QMC5883L to get the directional data through i2c. I also have a L298N breakout module to drive the wheels (BO motor setup), a battery pack with a switch that I'm using to power the motor driver and arduino. The battery pack is li-ion in 1S5P config. So I'm using a boost converter to step up the voltage to 12v for the L298N and a buck converter to bring down the 12V to 5V for arduino and 5883L. I understand this may not be the most efficient way to do it but this is just a temporary setup.
I have just started this project, as the first step I have managed to successfully obtain the data from the 5883L. Initially I didn't use pull up resistor on i2c, now I'm using 2k7 resistor for pullup (5883L is working on 5V). Now I'm trying to orient the robot to a direction (using north direction for the test). If the robot is facing towards east it'll turn counter clockwise to get oriented to north and if it is facing towards west it'll turn clockwise. This is the idea for the second step and the Issue starts here. The arduino is hooked up to the USB and is working fine. As soon as I turn on the battery pack switch (with the USB still connected), it runs for a moment and then freezes. It'll just run the last executed line. The motor doesn't start to run until I turn the battery pack on.
I tried to debug using serial monitor. The code is running fine but for some reason freezes when the motor is turned on. I made sure the GND is connected properly. I tried disconnecting one of the motor terminal from the L298N module and the code seems to work perfectly fine. The moment I connect a motor to the driver module, the serial monitor seems to slow down a bit. The code will then run for a very little time and will freeze as the motor gains speed.
Every time the code freezes I'll have to manually reset the board.
I tried to isolate the arduino and motor driver but I still have to ground them together in order for the motor to work, this idea didn't work.
For some reason the code will only freeze when the motor is spinning. I don't know if there is any interference coming from the motor. I tried adding a 1000uF capacitor to the supply of the L298N, added decoupling capacitors to the motor, added pullup resistor to i2c lines (started with 5k ohms and went down to 2k7).