0

I want to control a servomotor via a Python Gui (PyQt) component "QDial". Hopefully the servomotor should rotate "simultaneously" with the Dial in GUI.

enter image description here

Below is the related code:

Arduino

void loop(){

   // while(!Serial){} //
   if(Serial.available()>0){        
       posOrder = Serial.readString(); // get Angle-Value from Serial
        
       // write to Serial Monitor 
        Serial.print("Set Servo Position to: ");   
        Serial.println(posOrder);

        int angle = posOrder.toInt();
        myservo.write(angle);    
        Serial.flush();
     
        delay(30);
    }
}

Qdial

## ....some code...

   self.dial.valueChanged.connect(self.writeToSerial)

## ...

def writeToSerial(self):  
    # create serial connection
    self.ser = serial.Serial(self.portPath, timeout=None, baudrate=self.baudRate)
      
    self.posAngle = self.dial.value()  # get value
    self.ser.write(str(self.posAngle).encode()) # write to Serial

Problem

When I click on the tick of the Dial, it works pretty well. After click, the function dial.valueChanged.connect(self.writeToSerial) will call the function writeToSerial(), which has enough time to write dial value to the Serial. The serial monitor shows:

Set Servo Position to: 65
Set Servo Position to: 30
Set Servo Position to: 170

But when I rotate the dial by holding the left mouse button, the function dial.valueChanged.connect(self.writeToSerial) will be called in each small step. It means, the function writeToSerial() will be crazy frequntly called and the serial.write() function can't write data in time. The serial monitor shows something like:

Set Servo Position to: 65666770717273747677
Set Servo Position to: 99100104108109114116119122126128130131133
Set Servo Position to: 1411421431441451461481501521541561

I can als use self.dial.sliderReleased.connect(self.writeToSerial) to make it triggered only once the left mouse button is released. But in this way, the servo motor can't rotation with dial "simultaneously"

Question

How to solve this Problem? to let the servo motor rotate "simultaneously" with dial

  • 1
    Try writing the newline character \n after the posAngle value. That will be the delimiter between the individual numbers – chrisl Jul 4 at 21:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.