PySerial is not reading Arduino serial output correctly

Hi,

I am trying to record encoder ticks for a set input for a set time period. I've written the following code for the Arduino Mega. I get the expected output in the Arduino Serial window but the tick value gets truncated to 3 digits when I use python to read the serial output. What am I doing wrong here?

#include "Arduino.h"
#include <digitalWriteFast.h>
#include <elapsedMillis.h>

#define cEncoderInterrupt 4
#define encoderPinA 19
#define encoderPinB 25

volatile bool encoderBSet;
volatile long encoderTicks = 0;

elapsedMillis timeElapsed;

int pwm_a = 3;
int dir_a = 2;
unsigned int pwmLow = 3000;
unsigned int pwmHigh = 7000+pwmLow;
int val;

void setup()
{
  Serial.begin(115200);
  pinMode(pwm_a, OUTPUT);  //Set control pins to be outputs
  pinMode(dir_a, OUTPUT);
  digitalWrite(dir_a,LOW);
  pinMode(encoderPinA,INPUT);
  digitalWrite(encoderPinA,LOW);
  pinMode(encoderPinB,INPUT);
  digitalWrite(encoderPinB,LOW);
  attachInterrupt(cEncoderInterrupt, HandleMotor, RISING);
}

void loop()
{
  if (timeElapsed < pwmLow)
  {
    val = 0;
  }
  else if (timeElapsed < pwmHigh && timeElapsed > pwmLow)
  {
    val = 200;
  }
  else if (timeElapsed > pwmHigh)
  {
    val=0;
    Serial.end();
  }
  
  analogWrite(pwm_a,val);
  Serial.print(encoderTicks);
  Serial.print(",");
  Serial.print(val);
  Serial.print("\r \n");
 
}

void HandleMotor()
{
  encoderBSet = digitalReadFast(encoderPinB);
  encoderTicks += encoderBSet ? +1 : -1;
}

This is my python code

import serial

fname = 'motorData.dat'
fmode = 'ab'

with serial.Serial('/dev/ttyACM0', 115200,timeout=3) as ser, open(fname,fmode) as outf:
	while ser.read():
		x = ser.readline()
		print x
		outf.write(x)
		outf.flush()
	ser.close()
	outf.close()

Thanks in advance!

I know little or nothing about Python but does that code perhaps keep opening and closing the serial connection to the Arduino ? If so, then be aware that opening the serial connection causes the Arduino to reboot.

Your Python code needs to open the serial port, allow time for the Arduino to reset and then keep the serial port open until it is completely finished with the Arduino.

Have a look at this Python - Arduino demo

...R