BLYNK
HOME       📲 GETTING STARTED       📗 DOCS       ❓HELP CENTER       👉 SKETCH BUILDER

NodeJS Blynk - Code Examples for Basic Tasks (Work in Progress)

nodejs
rpi

#1

As a complementary “Brother Topic” of my C++ based Example Code Topic, here is one dedicated to NodeJS for Blynk.


Index to date:


In order to keep this topic easy to reference and use, and from becoming a post fest of “help me” and “don’t work” comments, I would prefer if anyone has “how to” questions about a particular piece of code… That they create a NEW topic for themselves, along with reference to this topics relevant posting of the code in question.

You can also Private Message me about any edits or alternative coding that you think might be beneficial… I can then work with you on that and update my post.

Please, NO Messaging for one-on-one assistance… use the afore mentioned self-created topic so that everyone can benefit from the discussion.

I am going to try to keep each post labeled and solely about a particular piece of code or process. And thus constantly edited and updated so as not to require constant back and forth multi-post content about it. We will see how that works :thinking: Thus this topic will be constantly updated as time goes on… so I hope no one minds if it keeps showing up at the top :innocent:

Most will be just code snippets. You may need at least a basic understanding of how things work with RPi, JavaScript and Blynk in order to use some of these examples.

If and when applicable I will try to include a QR code for each example.


Set default values for some of my Widgets
I can't connect my raspberry with blynk by server local
C++ Blynk - Code Examples for Basic Tasks (Work in Progress)
Npm install -g node-dht-sensor fails to install
Blynk RPI 3 Model B+ connect to local server
Bit the bullet and installed Node.JS / Blynk on Rpi3. It's awesome
Onion Omega + node.js Blynk Library - How to write code
Camera pi connect to Raspberry with Blynk
Decprecation Warning
Change button without tapping
Need help with basic Blynk script for relay switch
#2

1 - Basic Install and Server Link

To start off with, here is how you set up your RPi for Blynk and you script for Blynk Server connection.

For Cloud Server:

const Blynk = require('blynk-library');  // Links variable 'Blynk' to the Blynk Library
const AUTH = 'xxxxxxxxxx';  // Your top secret auth code
const blynk = new Blynk.Blynk(AUTH, options = {
  connector : new Blynk.TcpClient()
});

For Local Server:

const Blynk = require('blynk-library');  // Links variable 'Blynk' to the Blynk Library
const AUTH = 'xxxxxxxxxx';  // Your top secret auth code
const blynk = new Blynk.Blynk(AUTH, options = {
	 connector : new Blynk.TcpClient( options = { addr: "xxx.xxx.xxx.xxx", port: 8080 } )  // This takes all the info and directs the connection to you Local Server.
	 });

Port 8441-8444 is blocked on my ISP
#3

2 - Simple “Delay/Pause” Function

Here is a simple “Delay/Pause” function that EDIT appears to be blocking… will post a better option soon :blush: )

// Adjustable sleep/delay function
function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

Usage is like this…

sleep(1000);  // Wait a second before proceeding

And thanks to @zeeko for pointing me in the right direction with some code snippets.

Here is a silly little routine for Blinking a Virtual LED when the button is on.

There is probably much nicer ways of doing this, but it works and shows how an interval and timeout timer work.

const BlinkButton = new blynk.VirtualPin(26);  // Setup Button Widget
const BlinkLED = new blynk.VirtualPin(27);  // Setup LED Widget
var intervalId;

BlinkButton.on('write', function(param) {  // Watches for virtual Blink Button
  if (param == 1) {  // If Button OFF
		run();
		} else if (param == 0) {  // If Button ON
			stop()
			}
});


function run() {
	intervalId = setInterval(blinkON, 1000);  // Repeat every second
}

function stop() {
	clearInterval(intervalId);
}

function blinkON() {
	blynk.virtualWrite(27, 255);  // Virtual LED OFF
	setTimeout(blinkOFF, 500);  // Run in 1/2 second
}

function blinkOFF() {
	blynk.virtualWrite(27, 0);  // Virtual LED ON
}

How to use Blynk with Javascript Environment
Timing references to RPi & NodeJS
#4

3 - Display Widget based Clock

Very basic, multiple Display Widget based Clock.

image

Display Widgets need to be set with frequency times… I run my full testbench script 24/7 and have had no problems with 1 min for both HOURS and MINUTES, and 1 sec for SECONDS

// ----- Clock Time Displays -----
var DisplaySeconds = new blynk.VirtualPin(9);  // Setup Display Widget for Seconds
var DisplayMinutes = new blynk.VirtualPin(11);  // Setup Display Widget for Minutes
var DisplayHours = new blynk.VirtualPin(12);  // Setup Display Widget for Hours

DisplaySeconds.on('read', function() {  // Widget calls for data
  DisplaySeconds.write(new Date().getSeconds());  // Sends the seconds 0-59 to the Display Widget
});
DisplayMinutes.on('read', function() {  // Widget calls for data
  DisplayMinutes.write(new Date().getMinutes());  // Sends the minutes 0-59 to the Display Widget
});
DisplayHours.on('read', function() {  // Widget calls for data
  DisplayHours.write(new Date().getHours());  // Sends the hours 0-23 to the Display Widget
});

RPI wiringPi DHT22 error
#5

4 - Joystick controlled Pan & Tilt Servo

I intentionally used the same vPins as the physical GPIO just for coding consistency, you can use most any pins you want.

const Gpio = require('pigpio').Gpio;

// Joystick with Pan & Tilt Servos
const PAN_PORT = 22;
const TILT_PORT = 23;
const pan = new Gpio(PAN_PORT, {mode: Gpio.OUTPUT});
const tilt = new Gpio(TILT_PORT, {mode: Gpio.OUTPUT});
var JoyX = new blynk.VirtualPin(22);  // Setup Joystick X on V22
var JoyY = new blynk.VirtualPin(23);  // Setup Joystick Y on V23

JoyX.on('write', function(panValue) {  // Watches for Joystick X
  pan.servoWrite(panValue);  // Set Servo to value
});

JoyY.on('write', function(tiltValue) {  // Watches for Joystick y
  tilt.servoWrite(tiltValue);  // Set Servo to value
});

Help with DC motors and Joystick widget
#6

5 - Music Player Control Widget

The rarely used Music Player Control Widget… one of these days soon to control actual music on the RPi :stuck_out_tongue:

Right now this is just a working demo… controlling something (right now just the output of the display) via the Player buttons.

And also toggling between Stop and Play with a normal button (and synchronized feedback between the two)

image

image

// ----- Music Player Widget -----
var PlayerWidget = new blynk.VirtualPin(17);  // Setup BrightPi IR LED Button
var PlayerButton = new blynk.VirtualPin(18);  // Setup BrightPi IR LED Button
var PlayerDisplay = new blynk.VirtualPin(19);  // Setup BrightPi IR LED Button

// Activates the Player via button
PlayerButton.on('write', function(param) {  // Watches for button
  if (param == 0) {  // If PlayerButton OFF
    PlayerWidget.write('stop');  // Stop PlayerWidget
    blynk.syncVirtual(17);  // Sync PlayerWidget to process command
    } else if (param == 1) {  // If PlayerButton ON
    PlayerWidget.write('play');  // Play PlayerWidget
    blynk.syncVirtual(17);  // Sync PlayerWidget to process command
  }
});

// Player functions
PlayerWidget.on('write', function(param) {  // Watches for PlayerWidget
    PlayerDisplay.write(param);  // Shows Player Widget output on Display Widget
      if (param == 'stop') {  // If PlayerWidget 'stop'
        //
        PlayerButton.write(0);  // Toggle PlayerButton OFF 
        // Do something to STOP music/video/etc.
        //
      } else if (param == 'play') {  // If PlayerWidget 'play'
        //
        PlayerButton.write(1);  // Toggle PlayerButton OON
        // Do something to PLAY music/video/etc.
        //
      } else if (param == 'prev') {  // If PlayerWidget 'play'
        //
        // Do something to skip BACKWARD to music/video.etc.
        //
      } else if (param == 'next') {  // If PlayerWidget 'play'
        //
        // Do something to skip FORWARD to music/video/etc.
        //
      }
});

#7

6 - Varying the intensity of a physical LED with a slider.

Let there be light… more light… less light… more light…

// ----- White LED -----
const Gpio = require('pigpio').Gpio;

const PhysicalWhiteLED = new Gpio(18, {mode: Gpio.OUTPUT});
var WhiteLEDintensity;
var WhiteLEDslider = new blynk.VirtualPin(0);  // Slider Widget on V0 for Pysical White LED intensity

// Vary the intensity
WhiteLEDslider.on('write', function(WhiteLEDintensity) {  // Watches for V0 Slider
PhysicalWhiteLED.pwmWrite(parseInt(WhiteLEDintensity));  // Sends PWM value to Physical LED (GPIO18)
});

#8

7 - Terminal Repeat

A simple Terminal repeating function, with added Time and Date.

image

// ----- Repeat terminal input -----
var term = new blynk.WidgetTerminal(13);  // Setup Terminal Widget

term.on('write', function(data) {
 term.write('You wrote:' + data + " @ " + new Date().toTimeString() + " " + new Date().toDateString() + '\n');
});

Terminal widget using raspi
#9

4 posts were split to a new topic: Timing references to RPi & NodeJS


Timing references to RPi & NodeJS
#11

A post was merged into an existing topic: Timing references to RPi & NodeJS


#12

8 - Reboot or shutdown RPi from Button Widget

I use this for reboot… just remove the -r for shutdown.

var process = require('child_process'); // Allows this script to run CLI commands

// ----- RPi Reboot Command -----
var RPiReboot = new blynk.VirtualPin(20);  // Setup Reboot Button

RPiReboot.on('write', function(param) {  // Watches for V20 Button
  if (param == 1) {  // Runs the CLI command if the button on V20 is pressed
    process.exec('sudo /sbin/shutdown -r', function (msg) { console.log(msg) });
}
});

#13

#14

9 - Blinking LED Widget from Button Widget

Extrapolate the various timer options for all your timing needs.

  • setInterval(functionCall(), timeInMillis); // Repeating interval

  • setTimeout(functionCall(), timeInMillis); // Run function once in x amount of time

  • myTimerID = setInterval(functionCall(), timeInMillis); // Use IDs for use with other options like...

  • clearInterval(myTimerID); // stop a normally repeating timer.

And probably more that I haven’t tried yet :stuck_out_tongue_winking_eye:

// Timed function to blink virtual LED
const BlinkButton = new blynk.VirtualPin(26);  // Setup Blinking Button Widget
const BlinkLED = new blynk.VirtualPin(27);  // Setup Blinking LED Widget
var intervalId;  // Assign this name to a variable

BlinkButton.on('write', function(param) {  // Watches for virtual Blinking Button
  if (param == 1) {  // If Button OFF
		run();  // Start the timer
		} else if (param == 0) {  // If Button ON
			stop()  // End the timer
			}
});


function run() {
	intervalId = setInterval(blinkON, 1500);  // Assign an ID to a timer and repeat function call every 1.5 seconds
}

function stop() {
	clearInterval(intervalId);  // Stop any running timer with this ID
}

function blinkON() {
	blynk.virtualWrite(27, 255);  // Virtual Blinking Blue LED Widget ON
	setTimeout(blinkOFF, 750);  // Run function call once in 0.75 seconds
}

function blinkOFF() {
	blynk.virtualWrite(27, 0);  // Virtual Blinking Blue LED Widget OFF
}

setTimeout in node.js