Bluetooth HC-06 disconnects after a few minutes.

IF your project works at all, it suggests your code is kosher, but maybe you are taking a risk with software serial at 38400, and might either change to hardware serial or reduce speed to 9600. I bet you don't have a good reason to run it at 38400. IF it works initially AND then dies, it suggests inadequate power, about which you say nothing. Please don't tell us you are running it on a 9v PP3.