How to get serial timeout in microseconds in python

code of python is as bellow:

import serial
import time

serialcomm = serial.Serial('/dev/tty.usbmodem14201', 9600)
serialcomm.timeout = 1

p = 0
while p <= 360:
    i = 'r,1,10000'
    serialcomm.write(i.encode())
    time.sleep(0.01)
    print(serialcomm.readline().decode('ascii'))
    p += 1

serialcomm.close()

code of Arduino is as bellow:

int dirpin = 3;
int pulpin = 4;
int enapin = 5;
String mystring;
int mtime = 30;
int t = 0;

void setup() {

  Serial.begin(9600);
  Serial.println("Write Direction (if Left = l, Right = r), Write Angle, speed");
  Serial.println("You Write bellow Direction, Angle & Speed");
  pinMode(dirpin, OUTPUT);
  pinMode(pulpin, OUTPUT);

  pinMode(enapin, OUTPUT);
  digitalWrite(enapin, LOW);

}

void loop() {

  mystring = Serial.readString();
  String xval = getValue(mystring, ',', 0);
  String yval = getValue(mystring, ',', 1);
  String zval = getValue(mystring, ',', 2);


  if (xval == "l")
  {
    digitalWrite(dirpin, LOW);
    float s1 = yval.toFloat();
    //t = zval.toInt();
    //t = constrain(t, 1, 9970);
    //mtime = (10000 - t);
    startrotation(s1);
  }
  if (xval == "r")
  {
    digitalWrite(dirpin, HIGH);
    float s1 = yval.toFloat(); 
    //t = zval.toInt();
    //t = constrain(t, 1, 9970);
    //mtime = (10000 - t);    
    startrotation(s1);
  }
}

String getValue(String data, char separator, float index)
{
  int found = 0;
  int strIndex[] = { 0, -1 };
  int maxIndex = data.length() - 1;

  for (int i = 0; i <= maxIndex && found <= index; i++) {
    if (data.charAt(i) == separator || i == maxIndex) {
      found++;
      strIndex[0] = strIndex[1] + 1;
      strIndex[1] = (i == maxIndex) ? i + 1 : i;
    }
  }
  return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}

void startrotation(float s1) {


  for (float x = 0.0; x < (s1 / 0.1125); x++)
  {
    digitalWrite(pulpin, HIGH);
    delayMicroseconds(30);
    digitalWrite(pulpin, LOW);
    delayMicroseconds(30);
  }
}

above is my program i would like to decrease delay time in program what can i do for that?
program is use for rotate stepper motor. in the program "r - says right side rotation, 1 - 1 degree rotation and 10000 is speed of motor.

At the Arduino side, don't use readString. It will wait for data till it times out. I suggest that you read Robin's Serial Input Basics - updated to get ideas.

There is a matching python topic: Demo of PC-Arduino comms using Python.

I'm not a python programmer so can't advise in detail.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.