It might not solve it because you keep on using serial.begin and serial.end.
For that code, it might have to be done after each serial.begin.
Why do you use serial.begin and serial.end all the time? Usually one sets up the serial port once in setup and does not use serial.end.