13: FPGA (DPL) controls servo motor

In this tutorial, we are going to write Verilog code to control servo motor. The servo SG-90 is manufactured by Waveshare. When you buy the servo motor, you may receive a datasheet that lists the operating voltage, maximum torque and the proposed Pulse Width Modulation (PWM)...etc. However, the FPGA DuePrologic provides input voltage of 3.3V where the operating voltage of servo SG-90 is 5V - 7V. In the lack of electrical power, I will list my calibrated PWM in order to rotate the servo motor successfully.

Our task: The servo motor is rotated back and forth with the period of 5 seconds

Step 1: Build electronic circuit






Step 2: Set up pin planner

Click "Start I/O Assignment Analysis" to check if the pin planner is set correctly. Otherwise, you have to import all port names by yourself.



Step 3: Verilog code

We create a timer "servo_count". When "servo_A" is HIGH, the PWM is 1.5ms and hence the servo is located at 120 deg. In contrast, when "servo_A" is LOW, the PWM is 0.15ms  and therefore the servo is stayed at 0 degree.

assign            XIO_2[3] = servo_pulse;  //for V'

reg [31:0] servo_count;
initial begin
servo_count <= 32'b0;
servo_A <= 1'b0;
end

always @(posedge CLK_66)
begin
    servo_count <= servo_count + 1'b1;
    if(servo_count > 400000000)  //Clock cycle 66MHz, 1/66M * 400000000 ~ 5 seconds
    begin
         servo_A <= !servo_A;
         servo_count <= 32'b0;
    end
end

 reg [31:0] ex_auto;
 initial begin
 ex_auto <= 32'b0;
 servo_auto <= 1'b0;
 end

always @(posedge CLK_66)
begin
    if(servo_A==1'b1)
    begin
    ex_auto <= ex_auto + 1'b1;
    if(ex_auto > 100000)  //Clock cycle 66MHz, this PWM is ~1.5ms,  servo rotates to 120 deg
    begin
         servo_auto <= !servo_auto;
         ex_auto <= 32'b0;
    end
    end
    if(servo_A==1'b0)
    begin
    ex_auto <= ex_auto + 1'b1;
    if(ex_auto > 10000)  //Clock cycle 66MHz, this PWM is ~0.15ms,  servo rotates to 0 deg
    begin
         servo_auto <= !servo_auto;
         ex_auto <= 32'b0;
    end
    end
end

Step 4: Upload Verilog code

Click "Start Compilation". If no error message is displayed, go to "Programmer" to complete hardware setup. Remember to update the pof file in "Change file" if necessary. The click "Start" to upload the code


After all, you should see that the servo motor is rotated periodically.

Video demo

Comments