2n2222 NPN low side switch not working with 31V
You need to connect 0V of your RaPi to the emitter connection on your power supply because you cannot drive dc current into the base without a return path for that current.

But, before you do that make sure that the 31 V dc supply can connect to 0V on the RaPi safely i.e. is the 31 V supply isolated from ground?

It may be OK if it isn't but tread carefully because I don't want you to destroy your RaPi.