在 Raspberry PI 2 上使用 java 和 Pi4J 控制伺服的问题

Problems with controlling a servo with java and Pi4J on a Raspberry PI 2

我想使用 Pi4J 通过 Raspberry PI 的 GPIO 引脚控制 MG90S Servo

我创建了一个 Java 应用程序,它有一个 hz 和一个占空比 ("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);

        }
    }
}

示例 1: 通过以下输入,我希望伺服处于 旋转.

赫兹:50 高毫秒:1

结果:舵机如预期在

示例 2: 通过以下输入,我预计伺服处于 180° 旋转。

赫兹:50 高毫秒:2

结果:舵机在~80°

有人知道我做错了什么吗?

我在另一个伺服器上遇到了类似的问题(我认为这是 arduino 的东西)。

我只是校准了给定的值,结果是正确的。我不知道它来自哪里,但伺服做了我想做的。

问题与Pi4J无关。睡眠时间不够准确

"The granularity of sleeps is generally bound by the thread scheduler's interrupt period. In Linux, this interrupt period is generally 1ms in recent kernels. In Windows, the scheduler's interrupt period is normally around 10 or 15 milliseconds" - qwerty