Talking with Arduino using Telegram and JavaScript

How to use Telegram API and Johnny-Five to interact with your Arduino.

In my experiments with this “internet of things” I was always limited to the wi-fi network in the place that I was running my code, but one day I saw this nice module to deal with Telegram bots using Node.js and now I can communicate from any place with internet using the app.

A simple dialog with the bot :)

When I did a talk at Nodebots International Day in Porto Alegre I showed how to create a server and associate specific routes with sensors/motors/leds. This allows anyone to type a specific url on the browser (doesn’t matter if notebook, tablet, smartphone, etc) and to communicate with the Arduino. Something like

http://192.168.0.3/servo/angle/90

sets the servo angle to 90 degrees position. Or

http://192.168.0.3/buzzer/300

plays the 300 Hz frequency on the buzzer for a predetermined time on code.

The code of this examples is here.

This is useful but I still want to know the sensor status even when I was really far from it. There are some services and platforms that solve this problem but some need specific hardware and I didn’t want to buy anything. One day in a JavaScript Weekly I read about the module above and *boom*. We have a very simple interface!

I created a repo on Github called Johnny-Telegram (because I’m very creative to name things) with some examples.

In the first case we will control a led. The code that should run to control the Arduino is below:

And so we can send a command by the telegram

call led blink 500

calling the ‘blink’ method with 500 as parameter. The answer should be

led.blink called with

And now we can call the methods that are exposed by Johnny Five API!

In the second example we will add a proximity sensor:

We’re calling the Johnny-Telegram ‘setValue’ method every time that we have data on sensor, so we can access the current value with a command on telegram:

value prox

And the response is:

18.522

Now we can send commands and receive data!

But maybe you want to receive a message if the distance is above or below of a specific value. So you can use ‘majorthan’ or ‘minorthan’:

majorthan prox 40cm 40 0.5

This command adds a trigger called “40cm” that checks if the sensor value is bigger than 40 each 0.5 minutes. The response that confirms if the command was well succeed is:

added as 40cm

If the values fits the conditions, a message is sent to you:

prox, 40cm = 42.348

Again, there are countless ways to do this communication, but a Node module to an app that I’m using everyday really motivated me to create this repo! And maybe to use JavaScript for it sounds bizarre, but remember even IBM thinks that is reasonable!