Servo control problems with java and Pi4J on Raspberry PI 2

I want to control the MG90S Servo via the GPIO pins of my raspberry PI using Pi4J.

I created a Java application with an hz step and a runtime ("High in ms:").

import java.util.Scanner;

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        GpioController gpioFactory = GpioFactory.getInstance();
        GpioPinDigitalOutput myServo =  gpioFactory.provisionDigitalOutputPin(
                    RaspiPin.GPIO_07, PinState.LOW);

        //Input of hz and duty cycle
        System.out.println("Hz:");
        Scanner scanner = new Scanner(System.in);
        float hz = scanner.nextFloat();
        System.out.println("High in ms:");
        float highTime = scanner.nextFloat();
        scanner.close();

        //Calculate GPIO low time: hz period time - duty time
        float lowTime = 1000 / hz - highTime;

        while (true) {
            myServo.high();
            long upMs = new Float(highTime).longValue(); // Up time miliseconds
            int upNanos = new Float(highTime * 1000000 % 1000000).intValue(); // Up time nanoseconds
            java.lang.Thread.sleep(upMs, upNanos);

            myServo.low();
            long lowMs = new Float(lowTime).longValue();
            int lowNanos = new Float(lowTime * 1000000 % 1000000).intValue();

            java.lang.Thread.sleep(lowMs, lowNanos);

        }
    }
}

      

Example 1: On next input, I expect the servo to be 0 Β° Rotation.

hz: 50 high to ms: 1

Result: The servo is at 0 Β° as expected.

Example 2: On next input, I expect the servo to be 180 Β° Rotation.

hz: 50 high to ms: 2

Result: The servo rotates ~ 80 Β° .

Does anyone know what I am doing wrong?

+3


source to share


2 answers


The problem had nothing to do with Pi4J. The sleep period was not accurate enougth.



"Sleep specularity is usually associated with the thread scheduler interrupt period. On Linux, this interrupt period is usually 1ms in recent kernels. On Windows, the scheduler interrupt period is usually around 10 or 15 milliseconds" - qwerty fooobar.com/questions/208445 / ...

0


source


I had a similar problem with another servo (I think it was arduino stuff).



I've just calibrated these values ​​so that the result is correct. I don't know where this is coming from, but the servo did what I want.

0


source







All Articles