reorganised code for serial communication