Luigi Francesco Cerfeda
Published © GPL3+

Using Python to Control Servo Motors for IoT Projects

In this tutorial, we'll see how to control a servo motor via mobile using Python and JQWidgets.

BeginnerFull instructions provided2 hours5,185

Things used in this project

Hardware components

MikroE Flip & Click
×1
MikroE Click Wifi 4
×1
Servos (Tower Pro MG996R)
×1
Jumper wires (generic)
Jumper wires (generic)
×1

Software apps and online services

Zerynth Studio
Zerynth Studio

Story

Read more

Schematics

Servo connections

Code

Control Servo via Zerynth App

Python
# Control Servo via Zerynth App
 
from wireless import wifi
 
# change the following line to use a different wifi driver
from stm.spwf01sa import spwf01sa as wifi_driver
 
from servo import servo
 
import streams
 
# Import the Zerynth APP library
from zerynthapp import zerynthapp
 
# connect the Servo to the pin D2
MyServo=servo.Servo(D2.PWM)
 
streams.serial()
 
degree = 0
 
sleep(1000)
print("STARTING...")
 
try:
    # Device UID and TOKEN can be created in the ADM panel
    zapp = zerynthapp.ZerynthApp("DEVICE UID", "DEVICE TOKEN")
    wifi_driver.init(SERIAL1, D16) # WiFi Click on slot    
    
    for i in range(0,5):
        try:
           # connect to the wifi network (Set your SSID and password below)
            wifi.link("SSID",wifi.WIFI_WPA2,"PASSWORD")
            break
        except Exception as e:
            print("Can't link",e)
    else:
        print("Impossible to link!")
        while True:
            sleep(1000)
 
    # Start the Zerynth app instance!
    # Remember to create a template with the files under the "template" folder you just cloned
    # upload it to the ADM and associate it with the connected device
    zapp.run()
 
    def set_degree(d):
        global degree
        degree = d
        MyServo.moveToDegree(degree)
 
    zapp.on("set_degree", set_degree)
    
    while True:
        sleep(50)   
        print("degree: ", degree)
 
except Exception as e:
    print(e)

Code snippet #2

Plain text
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        
        <title>Zerynth</title>
        <!-- LOAD JQUERY AND BOOTSTRAP -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <!-- LOAD THE ZERYNTH ADM JS LIBRARY -->
        <script src="https://api.zerynth.com/zadm/latest/z.js"></script> 
        <!-- LOAD jqwidget.js -->
        <link rel="stylesheet" href="https://jqwidgets.com/public/jqwidgets/styles/jqx.base.css" type="text/css" />
        <script src="https://jqwidgets.com/public/jqwidgets/jqx-all.js"></script>
        <script type="text/javascript" src="https://www.jqwidgets.com/public/jqwidgets/jqxcore.js"></script>
    </head>        
    <body>
        <div style="text-align:center">
            <p id="status" style="background:#ddd;font-weight:bold"></p>
            <h1>Set Degree</h1>
        </div>
        <div id='jqxKnob' style="width: 150px; height: 150px; position: relative; left: 30; top:30">
        </div>
        <script>
             $(document).ready(function () {
                $('#jqxKnob').jqxKnob({
                    width: 300,
                    value: 0,
                    min: 0,
                    max: 180,
                    startAngle: 0,
                    endAngle: 180,
                    snapToStep: true,
                    rotation: 'counterclockwise',
                    style: { stroke: '#dfe3e9', strokeWidth: 3, fill: { color: '#fefefe', gradientType: "linear", gradientStops: [[0, 1], [50, 0.9], [100, 1]] } },
                    marks: {
                        colorRemaining: { color: 'grey', border: 'grey' },
                        colorProgress: { color: '#00a4e1', border: '#00a4e1' },
                        type: 'line',
                        offset: '71%',
                        thickness: 3,
                        size: '6%',
                        majorSize: '9%',
                        majorInterval: 10,
                        minorInterval: 2
                    },
                    labels: {
                        offset: '88%',
                        step: 30,
                        visible: true
                    },
                    progressBar: {
                        style: { fill: '#00a4e1', stroke: 'grey' },
                        size: '9%',
                        offset: '60%',
                        background: { fill: 'grey', stroke: 'grey' }
                    },
                    pointer: { type: 'arrow', style: { fill: '#00a4e1', stroke: 'grey' }, size: '59%', offset: '49%', thickness: 20 }
                });
                $('#jqxKnob').jqxKnob({allowValueChangeOnDrag: false });
                $('#jqxKnob').jqxKnob({allowValueChangeOnMouseWheel: false });
                $('#jqxKnob').on('change', function (event) {
                    Z.call('set_degree', [event.args.value]); 
                });
 
                // initialize the Z object
                Z.init({
                    on_connected:  function(){$("#status").html("CONNECTED")},
                    on_error:  function(){$("#status").html("ERROR")},
                    on_disconnected:  function(){$("#status").html("DISCONNECTED"); return true},
                    on_online:  function(evt){$("#status").html("ONLINE");},
                    on_offline:  function(evt){$("#status").html("OFFLINE");},
                    on_event:  function(evt){
                        //display received event; 
                    }
                  })
            });
         
        </script>
        
    </body>
</html>

Credits

Luigi Francesco Cerfeda

Luigi Francesco Cerfeda

6 projects • 95 followers
Yet another Tony Stark wannabe

Comments