pyserial trouble

Hello there

I’m trying to send two unsigned integer-values with a structure pack from python to arduino. The arduino reads the buffer and sends the value back as conformation. The stepper motor i want to control takes this value as the input of the amount of steps he has to do.
The problem is: Even if i send two times the exact same value to the arduino, the stepper motor changes direction out of nowhere. But when I hardcode the value in the arduino code(So I overwrite the inputarray ,which freshly read the input buffer, with a fixed value, everything works perfectly).
I use a stepper motor with a two pin control(dir, step).

I’m a beginner. So I appreciate code improvement tips also.

Thank you in advance! :slight_smile:

if(Serial.available()== 2){
      for(int i = 0; i < 2; i++){
        c =;
        incoming[i] = (int)c;
      Serial.write(incoming[1]);//write back success message

      //incoming[0] = 13;
      //incoming[1] = 15; //this works perfectly. interpretation of byte broken
      if(incoming[0]<127){ //set direction 
        digitalWrite(S1dirPin, HIGH);
        digitalWrite(S1dirPin, LOW);
        incoming[0] = incoming[0] - 127;//shift number
      if(incoming[1]<127){ //set direction 
        digitalWrite(S2dirPin, LOW);
        digitalWrite(S2dirPin, HIGH);
        incoming[1] = incoming[1] - 127;
      if(incoming[0] > incoming[1]){
        bigger = incoming[0];
        smaller = incoming[1];
        bigPin = S1stepPin;
        bigState = step1_state;
        smallState = step2_state;
        smallPin = S2stepPin;
        time_part = (bigger*2-1)/(smaller*2-1);
        bigger = bigger*2-1;
        smaller = smaller*2-1;
        bigger = incoming[1];
        smaller = incoming[0];
        bigPin = S2stepPin;
        bigState = step2_state;
        smallState = step1_state;
        smallPin = S1stepPin;
        time_part = (bigger*2-1)/(smaller*2-1);
        bigger = bigger*2-1;
        smaller = smaller*2-1;

      start = 1; //starts step-sequence

  if((micros()- time_now1 > time_min) && (bigger > 0) && start){
    time_now1 = micros();
    digitalWrite(bigPin, !bigState);
    bigState = !bigState;

I can't figure out what you are sending to the Arduino.

Have a look at this Simple Python - Arduino demo and at Serial Input Basics - simple reliable ways to receive data.

IMHO it makes debugging much easier if you send data as text and I would not send binary data unless it was essential for performance.

If you do want to send binary data then just read all the bytes into a struct in the Arduino and the conversion will happen automatically.


I actually solved that problem. There was a problem with the millis() and mikros() function. I don't understand the problem, but it is solved now. Pyserial works perfectly.

thanks for the help :slight_smile: