/

Using Johnny Five to Receive Input from an Electronic Device

Using Johnny Five to Receive Input from an Electronic Device

tags: [“Johnny Five”, “Node.js”, “water level sensor”]

This blog post is part of the Johnny Five series. If you haven’t read the first post yet, you can find it here.

In this post, we will explore how to receive data from an electronic device using Johnny Five. Specifically, we will use a water level sensor to monitor the level of coffee in a cup. This will help us determine if we need to refill our cup to sustain our programming endeavors.

Water Level Sensor
Water Level Sensor

To wire the sensor, connect the pins as follows:

  • Connect the pin marked as - to GND (0V)
  • Connect the pin marked as + to VCC (5V)
  • Connect the pin marked as S to the analog pin A0

Circuit Wiring

Here’s the circuit diagram for reference:

Circuit Diagram

Now, let’s create a sensor.js file with the following content:

1
2
3
4
5
6
7
8
9
10
const { Board, Sensor } = require("johnny-five")
const board = new Board()

board.on("ready", () => {
const sensor = new Sensor("A0")

sensor.on("change", function () {
console.log(this.value)
})
})

Whenever the data from the sensor changes, the program will output the new value to the console.

Console Output

In addition to the change event, Johnny Five provides various methods for working with the sensor. One method of interest is within(), which allows us to define a callback that is triggered when the value falls within a specific range. For example:

1
2
3
4
5
6
7
8
9
10
const { Board, Sensor } = require("johnny-five")
const board = new Board()

board.on("ready", () => {
const sensor = new Sensor("A0")

sensor.within([0, 70], function () {
console.log("Refill your coffee!!")
})
})

In this example, if the coffee level falls below 70, the program will output “Refill your coffee!!” to the console.

Console Output
Water Level Sensor

To further enhance our coffee monitoring system, let’s introduce a variable called outOfCoffee to debounce the data gathering. We can use the within() method to define two separate callbacks. One for when the value is below 70, indicating that we are out of coffee, and another for when the value is above 150, indicating that we have enough coffee to continue our programming endeavors. Here’s the updated code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const { Board, Sensor } = require("johnny-five")
const board = new Board()

board.on("ready", () => {
const sensor = new Sensor("A0")
let outOfCoffee = false

sensor.within([0, 70], () => {
if (!outOfCoffee) {
outOfCoffee = true
console.log("Refill your coffee!!")
}
})

sensor.within([150, 500], () => {
if (outOfCoffee) {
outOfCoffee = false
console.log("Ok, you can go on programming!!")
}
})
})

With this updated code, if the coffee level crosses the threshold values, the appropriate message will be printed to the console.

Water Level Sensor
Console Output