Skip to content

Instantly share code, notes, and snippets.

@gylippus
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gylippus/8864200f4bf6e57d3293 to your computer and use it in GitHub Desktop.
Save gylippus/8864200f4bf6e57d3293 to your computer and use it in GitHub Desktop.

Introduction to Arduino

In this lesson we will learn about using Javascript to interact with hardware. We will be using a platform called Node.js which runs Javascript outside of the browser.

What is an Arduino?

Arduino is a tool for making computers that can sense and control more of the physical world than your desktop computer. It's an open-source physical computing platform based on a simple microcontroller board, and a development environment for writing software for the board. arduino.cc

Basic Circuitry

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. nodejs.org

!Arduino

Image adapted from: arduino.cc

Solderless breadboard

  • These are a cheap, easy and quick way to make circuits.
  • Inside the breadboard are many strips of metal that connect the rows and columns of holes together.
  • The metal strips are springy so that when you poke a wire into the hole, the clips grab onto it.
  • Between the blue and red lines are dual rows of 25 holes. 25 holes are joined together with a metal strip—this is a RAIL. The rail closest to the red line is positive, the rail closest to the blue line is negative.
  • In the middle of the breadboard are many 30 pairs of short rows of 5 holes each. 5 holes are joined together with a metal strip These are called, wait for it, ROWS.

Red wire

  • In wiring, the colour red conventionally means positive, and this wire is going from the 5V power socket on the Arudino to the positive rail.

Black wire

  • In wiring, the colour black conventionally means negative, and this wire is going from the negative rail to the ground (Gnd) socket on the Ardunio.

LED (Light Emitting Diode)

  • The positive LEAD is connected to a row, the negative lead is connected to the negative rail.
  • The name ‘diode’ means this small bulb works when current flows through it in one direction, but not the other direction.
  • The LED has one long ‘leg’ or LEAD which is positive, and one short lead which is negative.
  • At the end, if the LED isn’t working, it is probably the wrong way round. Try swapping where the leads are connected.

Resistor

  • The resistor is connected from the positive rail to the same row as the LED. It doesn’t matter which way round its connected.
  • We have to use a resistor in this circuit to protect the LED. Using an LED without a resistor is a sure-fire way to kill it! (You'll see a bright flash and then the LED may turn dark).
  • By putting the resistor in series with the LED, we can limit the amount of current flowing in the circuit and protect the LED.
  • In an LED, a small change in voltage can produce a huge change in current. Resistors aren’t like that—the current and voltage in a resistor are linearly related. That means that a change in voltage will produce a proportional change in current (V=IR).
  • Resistors have coloured bands which tell you how much resistance they have.

Before we start...

Required files

Download and install Node here

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. nodejs.org

Johnny-Five is Alive

What is Johhny-Five?

Johnny-Five is a javascript library for interacting with Arduino hardware. It provides us with API to make common input and output requests to the device. An API (Application Programming Interface) defines common methods and parameters that translate our commands to interact with a service.

Installing Johnny-Five

From the Terminal (Mac/Unix) or Command Prompt (Windows), change directories to get to the where you would like to start your project.

Create a new project directory and install Johnny-Five to that directory:

$ mkdir projectname
$ cd projectname
$ npm install johnny-five

1. Basic Program

Create a new file called basic.js and write the following code:

var five = require("johnny-five"),
    // or "./lib/johnny-five" when running from the source
    board = new five.Board();

board.on("ready", function() {

  // Create an Led on pin 13 and strobe it on/off
  // Optionally set the speed; defaults to 100ms
  (new five.Led(13)).strobe();
});

TODO:

Explaining the Physical Connections:

For this basic program we are using the Arduino Pin 13. This particular pin input has an integrated resistor which means we do not need to add our own.

Explaining the code:

require("johnny-five"), 'require' is used by node.js to import code dependencies that will be accessed by our program

board = new five.Board(); This line is creating a new Board object which is defined in the johnny-five library

Running our program:

Once you have saved the file. Return to the terminal and run:

$ node basic.js

2. Program with debugging inputs

Create a new js file called debug.js with the following code:

// Create board
var five = require('johnny-five');
var board = new five.Board();

// We set the proxy functions as noops for now
// as the board may not be ready by the time we
// start using the exported functions.

var noop = function () {};
var onLog = noop;
var onError = noop;
var onClear = noop;

// We patch the onLog, onError and onClear functions
// once the board is ready, so that subsequent calls 
// to our methods will affect the LED's as we want. 
var setupExports = function () {
  var redLED = new five.Led(13);
  var greenLED = new five.Led(14);

  onClear = function () {
    redLED.off();
    greenLED.off();
  };

  onError = function () {
    redLED.on();
  };

  onLog = function () {
    greenLED.on();
  };

};

// Add the listener 
board.on('ready', setupExports);

// Export our functions
module.exports = {
  log: function (msg) {
    onLog();
    console.log(msg);
  },
  error: function (msg) {
    onError();
    console.error(msg);
  },
  clear: function () {
    onClear();
    console.clear();
  }
};

Create a second file that imports and uses this module.

var debug = require('./debug');

debug.log('whatever');

debug.log('hello');

setTimeout(function () {
  debug.error('ugh oh theres been an error');
}, 1000);

setTimeout(function () {
  debug.clear();
  debug.log('Yay!');
}, 3000);

TODO:

Explaining the Physical Connections:

Run the Program

Run the program and experiment how you can make changes to the code in the second file to make different outputs to the hardware.

The idea of this file would be to react to live code and present visible error logging. Can you think of any ways to implement this in a real scenario?

## 3. Button as physical input

This program just lights our LED when the button is pressed, but will flash the LED when the button is held. We're using the five.Button object to read and act upon interactions with a physical button.

var five = require('johnny-five');
var board = new five.Board();

var main = function () {

  var led = new five.Led(13);
  var button = new five.Button(5);

  button.on('press', led.on);
  button.on('release', led.off);
  button.on('hold', led.strobe);

};

board.on('ready', main);

TODO:s

Explaining the Physical Connections:

Experiment:

  • Can you change the frequency of the strobe?
  • What happens if you don't use the hold event listener?
  • Can you make the button act more like a light switch?

4. Photoresistor as an input

This program will read data from a photoresistor and turn on our LED depending on the brightness.

A photoresistor or light-dependent resistor (LDR) or photocell is a light-controlled variable resistor. The resistance of a photoresistor decreases with increasing incident light intensity; in other words, it exhibits photoconductivity. wikipedia

Try creating and running this program and seeing the results, you may need to tweak the checkValue function for your environment, also take a look at the documentation for five.Sensor objects and try using the booleanAt method to make the check function cleaner.

var five = require('johnny-five');
var board = new five.Board();

var main = function () {
  var threshold = 300;
  var led = new five.Led(13);
  var sensor = new five.Sensor({
    pin: "A2",
    freq: 250
  });

  var checkValue = function () {
    if (sensor.value < threshold) {
      led.on();
    } else {
      led.off():
    }
  };

  sensor.on('data', checkValue);

};

board.on('ready', main);

TODO: show/hide

var checkValue = function () {
  if (sensor.boolean) {
    led.off();
  } else {
    led.on();
  }
}

TODO:

Explaining the Physical Connections:

Experiment!

  • What happens if you change the frequency of the sensor?
  • What happens if you change the threshold of the sensor?

Challenge:

  • Can you add a button to change the behavior of the sensor?
  • Try anything else you want!

Bonus

Explore the johnny-five API and the equipment available to you in order create your own project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment