Book Image

Hands-On Robotics with JavaScript

By : Kassandra Perch
Book Image

Hands-On Robotics with JavaScript

By: Kassandra Perch

Overview of this book

JavaScript has an effective set of frameworks and libraries that provide support for embedded device programming and the robotics ecosystem. You’ll be able to put your JavaScript knowledge to work with this practical robotics guide. The book starts by guiding you in setting up an environment to program robots with JavaScript and Rasberry Pi 3. You will build beginner-level projects, such as a line-following robot, and then upgrade your robotics skills with a series of projects that help you get to grips with the Johnny-Five library. As you progress, you’ll learn how you can improve your projects by enabling advanced hardware components and programming concepts. You’ll even build an advanced AI-enabled robot, connect its NodeBots to the internet, create a NodeBots Swarm, and explore Message Queuing Telemetry Transport (MQTT). By the end of this book, you will have enhanced your robot programming skills by building a range of simple to complex projects.
Table of Contents (19 chapters)
Title Page
Dedication
Packt Upsell
Contributors
Preface
Index

Getting a servo working with Johnny-Five


To get a servo working with Johnny-Five, we'll look at the Johnny-Five servo object, talk about wiring the servo to our PWM hat, and write our first piece of code to get the servo to sweep back and forth.

The Johnny-Five servo object

Looking at the servo page in the API section of the Johnny-Five documentation, we will look first for our constructor. Because we're still using the PCA9685 PWM hat, our constructor will look like this:

let servo = new five.Servo({
  controller: "PCA9685",
  pin: 0
});

As for moving the servo, there are a few method described in the docs to move the servo. The first move can be to a fixed position:

servo.to(degree)
servo.min()
servo.max()
servo.home() 
servo.center()

Or, another is to sweep back and forth, either as far back and forth as possible, or between a range:

servo.sweep() // goes 0-180 and back, then repeats
servo.sweep(minDegree, maxDegree) // goes min to max and back, then repeats

You can also stop a moving servo...