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.
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 pinA0
Here’s the circuit diagram for reference:
Now, let’s create a sensor.js
file with the following content:
1 | const { Board, Sensor } = require("johnny-five") |
Whenever the data from the sensor changes, the program will output the new value to the console.
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 | const { Board, Sensor } = require("johnny-five") |
In this example, if the coffee level falls below 70, the program will output “Refill your coffee!!” to the console.
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 | const { Board, Sensor } = require("johnny-five") |
With this updated code, if the coffee level crosses the threshold values, the appropriate message will be printed to the console.