Internet of Things, Fun With Node-Red, Smartphone Control, Raspberry Pi

2,355

28

Introduction: Internet of Things, Fun With Node-Red, Smartphone Control, Raspberry Pi

About: Engineer, retired. Have always had an interest in electronics, often related to radio control. This evolved into a part time business that I still practice. I do some voluntary work in schools to encourag...

This Instructable is targeted at beginners who want to get a glimpse of the wonderful world of Node-Red and the vast opportunities it opens for home automation, connected devices, home information, music systems – the list goes on. All the software/firmware is free and runs on the very low cost Raspberry Pi’s. These are run in ‘headless’ mode and so do not need any peripherals (screen, keyboard, mouse are not required). It has been written for a classroom environment where a local Wi-Fi network probably needs to be set up. This step is not required if a home Wi-Fi is available.

After initial setup we add a remotely controlled switch– controlled by smartphone(s). Then sound is added – then email – all very easy. Then we add control of a LED. Lastly we explore controlling Neopixel strings for some multi-coloured fun.

Steps:

  • Set up local Wi-Fi hotspot on PC/laptop (skip if home Wi-Fi available).
  • Make up the LED and Neopixel string connections
  • Load up the Pi with operating system, Node-Red and some extra nodes needed for this project.
  • Switch fun (led, sound and email control)
  • NeoPixel fun
  • Some Node-Red Capabilities to Explore

Supplies:

Raspberry Pi and SD card (suggest 8Gb+) (Pi 3A used here)

Wi-Fi USB dongle if the Pi does not have Wi-Fi on-board

PC/laptop with Ethernet and Wi-Fi connections (only needs internet if home Wi-Fi is available)

Smartphone(s)

LED and resistor

Neopixel string plus 1000uf capacitor 1N4001 diode and 330ohm resistor

Teacher Notes

Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.

Step 1: Set Up Local Wi-Fi Hotspot

This step is only needed if a local Wi-Fi is not available.

A laptop/PC can be set to work like a Wi-Fi router. It will need a USB Wi-Fi dongle (cheap on ebay) if Wi-Fi is not installed. Windows 10 is assumed. Sorry I have no access to a MAC.

This should have been as easy as going to Settings>Network & Internet>Mobile hotspot and clicking the switch above ‘Share my Internet connection with other devices’. But I got ‘We can’t setup mobile hotspot’. After several hours of following troubleshooting guides I eventually found an approach that worked.

During this process I learned that not all Wi-Fi adaptors can host networks. So the process I would follow is:

Check sharing is not enabled:

Go to Settings>Network and Internet>Change adaptor settings

If you see ‘shared’ against any of the entries do a right click and select Properties, then select the Sharing tab.

Now untick the ‘Allow other network users…..’, and click OK. If this was necessary also restart the PC so these get implemented.

Check your adaptor can support hosting:

Run ‘Command Prompt’ as administrator (start>all programs>Windows System, right click on 'Command Prompt' and select ‘Run as administrator’)

You should see:

C:\Windows\System32>

(If not Enter: CD \WINDOWS\system32 (copy this and right click to paste))

Now enter: NETSH WLAN show drivers (copy this and right click to paste)

Look down the text that appears for ‘Hosted network supported :’, that will hopefully say ‘yes’. If not then try another adaptor. The first one I found that worked was an EDIMAX dongle that was over 10 years old and only supported b and g modes! Then I checked one of the tiny cheap USB dongles that I keep handy for my older Pi's and that was OK as well. The Intel card in my old laptop was not able to host networks.

Leave ‘Command Prompt’ open for the next step.

Start hosted network:

Enter: NETSH WLAN set hostednetwork mode=allow ssid=Your_SSID key=Your_Passphrase

(In the above replace 'Your SSID' with desired network name and 'Your Passphrase' with a security code of at least 8 letters/digits)

Enter: NETSH WLAN start hostednetwork

It should look like:

Scary bit done! Close Command Prompt

Connect the hosted network to the PC Ethernet connection:

Back to Settings>Network and Internet>Change adaptor settings

Right click on Ethernet, select Properties, and then select the Sharing tab. Now tick the ‘Allow other network users…..’, and in the Home networking box select an entry that starts ‘Local Area Connection’ and click OK.

You should now have something like this:

PC restart.

Note that after any restart of my PC I had to restart the hosted network:

Run the Command Prompt as administrator and enter:

NETSH WLAN start hostednetwork

Then re-link the sharing. Go to Settings>Network and Internet>Change adaptor settings. Right click on Ethernet and select Properties, and then select the Sharing tab. Now untick the ‘Allow other network users…..’, and click OK. . Next again right click on Ethernet, select Properties, and then select the Sharing tab. Tick the ‘Allow other network users…..’, and in the Home networking box select an entry that starts ‘Local Area Connection’ and click OK.

Step 2: Make Up the LED and Neopixel String Connections

The LED is the easy one to do. One needs to select an appropriate current limiting resistor. The Pi outputs have a limit of around 16ma. The total consumption from all pins must also be limited. It is not clear by how much but 50ma seems to be accepted as OK. So I set a target of 8-10ma. With a red/green LED voltage of say 1.8v a resistor of 180ohms is OK and the more common 220ohms a safer alternate. For white/blue I use 2.8v drop. Hence a resistor of 68 ohms should be OK but I would go with 100 ohms to be safe. Ideally wire these to Dupont cables or direct to 0.1” spacing connectors if you have them. Alternatively use test clips but be careful to avoid short circuits. Note that LEDs usually have a flat on the package next to the negative lead.

LED soldered to resistor and wires:

LED complete with heatshrink and connector:

By Neopixels I consider strings using WS2812 chips or SK6812 or PL9823.

The Neopixel strings need a bit more consideration because they are normally run at 5v and hence the 3.3v logic signal from the Pi becomes marginal. The ideal solution is to use a logic converter to get the 3.3v signal up to 5v. However for this case we can go with a simpler option. These strings are typically rated down to 4.5v with a minimum of 3.5v. However beware – the voltage drop along the string can be significant. But here the plan is to only drive a few LEDs so this is less of a problem.

Hence we can drop the voltage (from 5v supply) with a diode (e.g. IN4001 series) which will give a supply around 4.3-4.5v that brings the Pi output voltage close enough to work. If the supply voltage gets too low no damage will be done but the colours will drift.

Adafruit recommend a 1000uf capacitor on the power connections of the strip and a resistor in series with the data line. Given our lower voltage logic I used 330 ohms for the latter.

Also note the current consumption – up to 60ma per pixel. Sometimes a good portion of a string will illuminate on power on – taking an amp or more current. This is much more than the Pi 5v pin is rated for and hence the string must be powered from a separate supply. Ground and data should be connected to the Pi.

The string I used had both a two wire power connector and a 3 way connector to the device supplying the the data. I decided to use test clips. The red and one black go to a 5v supply. The yellow and the other black go to the Pi (pins 12 and 14 respectively).

Step 3: Load Up the Pi

The setup process runs the Pi remotely throughout – also called headless mode. This avoids the need to connect a keyboard/mouse/screen.

Start by downloading the latest version on Raspbian from https://www.raspberrypi.org/downloads/. I used the lite version to avoid a load of stuff that will not be used here. Burn this onto a micro SD card using Etcher from https://www.balena.io/etcher/:

Etcher ejects the card when done so take it out and reinsert it for the next step (and ignore the Windows request to format the card).

In order to run headless we need to add two files to ‘boot’ before putting the card into the Pi. The first is a blank file called SSH. This tells the Pi to enable SSH from start-up. The second file is needed to give the Wi-Fi details so the Pi can connect. This latter file is called wpa_supplicant.conf and is of the form:

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev

network={

ssid="YOUR_NETWORK_NAME"

psk="YOUR_PASSWORD"

key_mgmt=WPA-PSK

}

Replace 'YOUR_NETWORK_NAME' and 'YOUR_PASSWORD' with either the network details set up in Step 1 or you home Wi-FI settings.

Plug the SD card into the Pi and power up.

Now we can log on. Use Putty from https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.htm. Enter the name raspberrypi and set port to 22. Now click ‘open’ and you should have the equivalent of the Pi terminal screen. Log on as pi with password raspberry. Note that the text entry can be copied from here and pasted into Putty (right mouse click). This saves a load of time!

We need to get the IP address for later so enter:

hostname -I

See output:

Now revise the password and other settings via:

sudo raspi-config (copy text then right click in Putty to paste)

First change the password

Under localisation set your Wi-Fi country.

Then right arrow twice and click Finish.

Next update the Pi software list by entering:

sudo apt-get -y update

Then upgrade entering:

sudo apt-get -y upgrade

This can take a while.

We now have the initial Pi setup complete.

Next load Node-Red. I have moved to a simpler and more reliable method to load Node-Red – following the approach at https://nodered.org/docs/hardware/raspberrypi . This uses a script and will install or upgrade Node-Red – so the approach is the same working from the full or lite versions of Raspbian. So enter:

bash <(curl -sL https://raw.githubusercontent.com/node-red/linux-installers/master/deb/update-nodejs-and-nodered)

Enter y when prompted (twice).

You will see the installation progress:

This script also loads files needed to enable autostart of Node-Red. So enter:

sudo systemctl enable nodered.service

Now do a restart:

sudo shutdown -r now

Leave Putty running if you want to include the Neopixel fun.

Now a little bit of administrative fun getting a couple add-ins we need for Node-Red.

Node-Red is accessed via its web page on the Pi at ‘Pi IP address’:1880 . (Use the IP address noted earlier) Enter this into a PC browser after the Pi has restarted.

It looks like:

The additional nodes are loaded via ’Manage Palette’ found via the ‘three horizontal lines’ icon top right. Select the Install tab and enter dashboard. Then next to ‘node-red-dashboard’ click install (and then Install again). Then for email search on email and install ‘node-red-node-email’.

For the Neopixel work we need to import Python and a python library. So right click the Putty title bar and select ‘Restart Session’. Log on, and then enter:

curl -sS get.pimoroni.com/unicornhat | bash

Enter y when prompted to continue and N when prompted for the full install and y to reconfigure audio and y to reboot.

When the Pi has restarted refresh your browser with Node-Red. Go back to ‘Manage Palette’ as above, select the Install tab and enter neopixel and install 'node-red-node-pi-neopixel'.

Step 4: Switch Fun

Log onto Node-Red from a PC/Laptop/tablet via its web page on the Pi at ‘Pi IP address’:1880 . (Use the IP address noted earlier)

Remote controlled switch

Now drag and drop 4 nodes from the left pane – 2 off inject nodes, a switch (from dashboard lower in the list) and a debug node. Drag wires to connect them so they look like:

We want the inject nodes to send 'on' and 'off' to the switch. So double click on one to get the edit node page. Click the twidly next to Payload and select string. Then enter on in the field and also put on in the Name field. Now do the same for the second inject node but enter off instead of on.

Now edit the switch node. This will appear on the user interface we will log onto shortly and so needs a page (tab) name and section (group) name. Click the pencil icon at the end of Group. A new page comes up. Enter Switch in Name. This page also needs a page(tab) name so click the pencil at the end of Tab and enter Switch Fun in Name. Now click ‘Done’

Change the On Payload to string (click the twidly) and on, and the Off Payload to string off, Click 'Done'

Now we are ready to play. When any changes have been made to a flow one has to click the Deploy button to make it live.

Click the tabs on the left on the on and off nodes and you will see the switch state change and a debug message showing the msg.payload will appear in the right hand pane. If you don’t see these make sure the ‘bug’ tab is selected.

Now let’s log onto the user interface. You can use the PC browser or grab your phone- or both, or several phones. Enter the address ‘Pi IP address’:1880/ui . You should see a switch – click it. Go back to the Node-Red flow. It is updated and the debug node gives a note of what has happened. So we are connected! If more than one device is logged on the switch position will be updated on the other devices as well.

A bit more on the right hand pane. There are several tabs. The ‘i’ tab gives information on the selected node. In most cases this has enough information to configure it.

The ‘bug’ tab is the Debug information we have been looking at. The graph tab is the user interface and can be used to move elements around. While we are here click it and then the Site tab and change the title to Node-RED Fun and then select the Theme tab and select style Dark. Click Deploy and see if you think this looks better.

Sound

Next let’s add some sound. Drag a dashboard 'audio out' node into the flow page, below and to the right of the switch. Wire it to the switch. Double click it to see the settings. Select the voice and tick the box next to ‘Play audio when window not in focus’. Click Deploy and see what happens. Note this feature requires the device showing the user interface to have a text to speech engine. It works on a PC and Android phones and I expect iphones as well (not tested).

We can make the sound output a bit more helpful using a function node. So drag a function node to the left of the audio out. Select and delete the wire from the switch to the audio out and rewire switch to function and function to audio out. Function nodes are amazingly powerful. They take any code in JavaScript and can have multiple outputs to trigger different nodes depending on the data input. Double click the function node. Enter Add text in 'Name' and enter the following code in line 1:

msg.payload = "The switch has changed to " + msg.payload;

Click Deploy and have a play.

Email

You can also send the text as an email. Skip this if you don’t have your email server and log on details. Add an email node, wire to the ‘Add text’ function output and edit it with the To, Server and UserrId and Password. This can be used to alert someone who is away from the local network.

LED

Next let’s drive a LED. Add a Raspberry Pi ‘rpi gpio out’ node and a function node. Wire the gpio out input to the function node output and the function node input to the switch output. The rpi gpio out node needs a 0 or 1 payload input so we need to convert on/off to 1/0.

Double click the function node. Enter Logic for the Name and add the following code (before the line with return):

if(msg.payload ==="on") {

msg.payload = 1;

}else {

msg.payload = 0;

}

Double click the rpi gpio out node and select the pin to be used. I selected ‘18 - GPIO24’ as it is not used for anything else and it is next to a ground pin.

Connect the LED + resistor, positive to pin 18 and negative to pin 20.

Click Deploy and again have a play.

By now you should have a feel for the power and ease of use of Node-Red. Please recognise that this is just the tip of the iceberg.

Step 5: NeoPixel Fun

Neopixels are great to play with. One can change every LED on a string of 60 to any of 16 million colours around 100 times a second (with the appropriate processor and code). The most popular Node-Red driver uses a Python library to implement the output and this is a little slower but also easier. Adafruit has a good guide and explanation of Neopixels if you want to delve deeper.

The plan is to drive several sections of the string independently from several colour pickers.

First create a new flow page for this work. Three lines icon>Flows>Add. Then rename it via Three lines icon>Flows>Rename and enter NeoPixel Fun and click ‘Done’.

To start add three nodes: a dashboard 'button', a function node and a Raspberry Pi 'rpi neopixels' node. Wire these together – button to function to neopixels. We will use these to setup a ‘clear’ string option.

Double click the button node so we can set it up. We want these controls in a new group on a new page(tab). Click the twidly at the end of the Group box and select ‘Add new ui_group’. Click the pencil icon to set this. Enter Controls into the Name box. Then click the twidly at the end of the Tab box and select ‘Add new ui_tab’. Click the pencil icon to set this. Enter Neopixel Fun into the Name box. Click Add, then Add again. Now set the size to 2x1. Lastly enter ‘Clear’ into the Label box and click ‘Done’.

Double click the function node, enter ‘Clear’ in the Name box and add the code

msg.payload = "#000000";

to line 1 of the function code. This is the colour RGB 0,0,0 that turns all off.

Click ‘Done’.

Double click the rpi neopixel node. Enter the number of pixels in the string – 60 in my case. Then enter 0,0,0 into both the Background and Foreground boxes. This turns these off. Click Done.

This is a good point to connect up the neopixel string. First power it up, then connect the ground to a ground pin on the Pi (e.g. pin 14) and then the data lead (via the 330ohm resistor) to pin 12.

Now click Deploy. The string should come to life showing red, green and blue followed by all off.

Now add a dashboard 'colour picker' and a function node. Wire 'colour picker' to function node to 'rpi neopixel' node.

Double Click the colour picker. Click the twidly to change the group to [NeoPixel Fun] Controls. Set the size to 4x4, enter 1 in the label box, set the format to ‘rgb’, untick the 'Show lightness slider', tick 'Always show picker', and set Payload to ‘current value as an object’. This latter setting makes it much easier to select the individual r, g and b values that we need to do in the function to convert the data into the format required by the rpi neopixel node. Click ‘Done’.

The data format required to set pixels x to y to the colour rgb is a string “x,y,r,g,b”. In this case we are going to set pixels 1 to 4 to the rgb from the colour picker. Double click the function node. Enter 1 to 4 as the Name and in the function code line 1 enter:

msg.payload = "1,4,"+msg.payload.r +","+msg.payload.g+","+msg.payload.b;

and then click 'Done'.

We need to do a bit of tweeking to the user interface. Click the dashboard tab (chart icon) in the right hand pane. On the Layout tab click and drag the 'NeoPixel Fun' above the 'Switch Fun'. This puts 'NeoPixel Fun' as the top page. Expand 'Controls', drag 'Clear' above '1' if necessary. Then, while hovering over 'Controls', click '+ spacer' and drag the spacer above 'Clear'. This moves the button away from the left edge.

Click ‘Deploy’ and open the Node-Red user interface page.

Now have a play changing the colour of the pixels 1-4.

We now need some more colour pickers to direct some more LEDs. Fortunately Node-Red supports copy and paste.

Click and drag over the colour picker and its associated function node. Enter ctrl+C to copy and ctrl+V to paste. Do the latter 3 times to create 3 more pairs of colour picker and function nodes.

Next edit each of the new colour pickers to give labels of 2,3,4 respectively. Then edit the function node associated with colour picker 2. Change the label to 6 to 9 and in line 1 of the code change 1,4, to 6,9, and click ‘Done’. Repeat this for the other two function nodes with labels 11 to 14 and 16 to 19 and changing the line 1 code 1,4, to 11,14, and 16,19, respectively. Add wires from each of the three new function nodes to the ‘rpi neopixel' node.

If there is more than one smartphone one can allocate each to one colour picker and they can all control their ‘own’ pixels independently at the same time.

Power off sequence:

It is best not to just turn the Pi off. Turning off without shutting down first risks corruption of the SD card.

So log back on using Putty and enter:

Sudo shutdown now

After a second you will get a dialog saying the connection has been lost. Wait a few more seconds. If the Neopixels are connected – first power these down, then the Raspberry Pi. If powering up again power up the Neopixels before the Pi.

Step 6: Some Node-Red Capabilities to Explore

A big strength of Node-Red is that is open source. I work on the assumption that if I want to do something with Node-Red that someone has been there before me and has written a node to do it. So it is always worth a search. There are also plenty of examples available to help get started.

Some examples of capability:

RS232 serial data – an old, simple but still used way of sending data between devices.

I2C – a widely used protocol that can be used to connect many sensors – e.g. for temperature, humidity, pressure, acceleration, rotation, gravity, and alpha numeric displays.

MQTT – a special protocol used widely in home automation. An open source system called Tasmota (5 million+ downloads!) can be used to modify some commercial devices to make a secure local system. Can also communicate with ESP-12 Wi-Fi boards (<£2) that in turn can be connected to sensors and even Neopixels that can be remote (but on the same network as the Pi). See:

Powerful Standalone Home Automation System - Pi, Node-Red
Home Automation Sonoff-Tasmota Sensors, LEDs, Neopixels

Twitter – can listen for feeds of interest.

Websites – can be directed to extract targeted information – e.g. BBC news stories.

Websites – can present information on websites hosted on the local network.

On-line data – e.g. log on and get weather information, extract data of interest and present them on a webpage.

Drive a Pi based music system (MPD) and create an MP3 player/internet radio. See:

HQ Music Player and Internet Radio With Smartphone Control

Send commands to run other programs on the Pi.

Kick off events based on time.

And of course there is loads more. Plus there are loads of customisation options such as changing colours and icons on the user interface.

I hope this Instructable gets you started coding with Node-Red.

Mike

STEM Contest

Participated in the
STEM Contest

Be the First to Share

    Recommendations

    • Trash to Treasure Contest

      Trash to Treasure Contest
    • Raspberry Pi Contest 2020

      Raspberry Pi Contest 2020
    • Wearables Contest

      Wearables Contest

    Discussions