Search code examples
javaraspberry-piservopi4j

Pi4j: SG90 doesn't turn all the way to 180°


I have this SG90 servomotor (completely functional and new) that doesn't turn all the way to 180° (or 0°).It stops halfway when i try to make it go right to left (counterclockwise). I have checked 4 times the wiring and the hardware so the problem is probably in the code. I am trying to control the servomototr through a raspberry pi3 with Pi4j.

I have already tried to change the wiring but i don't think that's the problem.

The code I tried to use was mine and what it did was to send PWM's of 1ms and 2ms.

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 xd {

    public static void main (String[] args) throws InterruptedException {

//creating the output

 final GpioController gpio = GpioFactory.getInstance();

        final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "MyLED", PinState.HIGH);

//making the 1ms PWM
//this makes the servo go left but it stops halfway to the end
 for (int i=0; i<=100; i++){

             pin.pulse(1,true);
             Thread.sleep(19);
         }

Now to the 2ms PWMs

//the servo goes right (clockwise) and it works fine
for (int i=0; i<=100; i++){

            pin.pulse(2,true);
            Thread.sleep(18);
        }



       gpio.shutdown();

}

}


Solution

  • hey myself i did more research than you and apparently you can directly output PWM signals without the need to make your own

    Here's an example:

    int n = 18;
    System.out.println("Config Servo PWM with pin number: " + n);
    com.pi4j.wiringpi.Gpio.pinMode(n, com.pi4j.wiringpi.Gpio.PWM_OUTPUT);
    com.pi4j.wiringpi.Gpio.pwmSetMode(com.pi4j.wiringpi.Gpio.PWM_MODE_MS);
    com.pi4j.wiringpi.Gpio.pwmSetClock(192);
    com.pi4j.wiringpi.Gpio.pwmSetRange(2000);
    
    for(int i = 0; i < 5; i++){
        System.out.println("Set Servo");
        com.pi4j.wiringpi.Gpio.pwmWrite(n, 50);
    
        Thread.sleep(1000);
    
        System.out.println("Change servo state...");
        com.pi4j.wiringpi.Gpio.pwmWrite(n, 250);
    
        Thread.sleep(1000);
    
    }