Controlling a servo motor through LAN

We controlled an LED remotely. The same program can be extended to control a micro servo motor. But buttons inside the webpage cannot give real control on an analog motor. So, we will use a slider/range input to control the micro servo motor.

HTML code

Open Cloud9 IDE and create a new file named servo.html. Write the following code in servo.html.

The code for servo.html is as follows:

<!DOCTYPE html>
<html>
<head>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io.connect();
    function pwm(value){
      socket.emit('pwm',value);
    }
  </script>
</head>

<body>
  <div>
    <label for="servo">Servo:</label>
    <input type="range" name="servo" id="servo" value="50" min="0" max="180" onChange="pwm(value);">
  </div>
</body>
</html>

This HTML code is similar to the code from the led.html file. Here, we used range instead of buttons. Here, the range/slider can have a value from 0 to 180. When the range is changed, we call the function pwm() with slider value as the parameter. The function pwm() emits a pwm event with a slider value as data. This sent event has to be handled on the server side.

JavaScript code

Now, let's write server side code to move a shaft of the micro servo motor based on the slider value emitted. This code is in addition to the previous baseHttpServer code. Create a new file in Cloud9 and copy-paste the previous baseHttpServer.js code as it is. Then append the following code and save it as IoTServo.js. You need to connect a micro servo motor to P9_14 pin as we did in the micro servo motor exercise in the last chapter. Please refer to the last chapter for a detailed image.

Run this IoTServo.js inside Cloud9 and open http://<Beaglebone's ip address>:3001/servo.html inside the browser on a smartphone/laptop/desktop. You will be able to see the slider on the webpage inside the browser. When you move the slider to max position, the micro server rotates to 180 degrees. When you move the slider to the minimum position, the micro servo rotates back to 0 degrees.

var b = require('bonescript'),

var sockio = require('socket.io'),
var servo = "P9_14";
var duty_min = 3;

var io = sockio.listen(myServer);

io.sockets.on('connection', connectionHandler);
function connectionHandler(socket)
{
  console.log("Inside connectionHandler");
  socket.on('pwm', pwmHandler);
  function pwmHandler(angle)
  {
    console.log("angle = " + angle); //print received data
    b.analogWrite(servo,((angle*0.064)+duty_min)/100, 60);
  }
}

You can combine connectionHandler() functions of both LED and servo code and get both HTML working in a single run. This program can be used to control a robotic arm remotely. The servo motor can be replaced with a DC motor to give you power to control the motor speed remotely.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.95.245