Sunday, 6 November 2016

Safety-First IoT Part 1 - Getting started with the Nano Pi NEO Air

Nano Pi NEO Air

On my Technology Policy Blog I've written about the challenges of The Internet Of Things, and how
to address them. Here on Make The Future I'm beginning this series of more technical articles on how
to put my recommendations into practice.

Meet the Nano Pi


The Nano Pi NEO Air is one of a number of low-cost boards inspired by the Raspberry Pi, many of which are
suitable for managing your own Internet of Things collection in the workplace or home.

The Raspberry Pi is a highly versatile single-board computer aimed at hobbyists, students
and Internet Of Things products. The Raspberry Pi occupies the "top of the line" position in this niche, with
WiFi, HDMI, Four USB-A ports, audio output, a gigabyte of RAM and top-notch software support.

An ecosystem of lower-cost alternatives have grown up, which aim at more specialised
subsets of the Raspberry Pi's market, typically by reducing features to save either size or cost.

The Nano Pi NEO AIR is the latest in a of a family of very small single board computers from FriendlyARM. The Air has the following notable features:

  • Tiny 40x40mm size
  • 8MB on-board flash pre-loaded with Ubuntu Linux
  • External WiFi antenna
  • Idle power consumption around 1 Watt (200mA @ 5V)
  • Weighs less than ten grams
  • No video output (but a dedicated 4-pin serial console connector)
  • No USB-A ports but (but headers for two external ports)

This board, which costs under US$20, is extremely well placed for mobile battery powered applications, or for IoT sensor applications that need the power offered. (My position is that if you don't need a Linux runtime in an IoT device, you should use a less complicated embedded platform with a smaller vulnerability surface instead).

One immediate application of the Nano Pi NEO Air is as a bridge for Apple's HomeKit, allowing you to control existing home-automation appliances via your iPhone (more on this in a future post).

Unboxing and Assembly

The Neo AIR is available from FriendlyARM with a number of optional extras. I recommend you order the following in addition to the board itself:

  • A case, either 3D printed PLA or laser-cut Acrylic
  • A heatsink (my board has run fine without a heatsink so far)
  • An external WiFi antenna

IMG_7593

If you don't already have a USB-to-TTL-serial converter, you will need one for initial setup. (See also my post on using a HC-06 Bluetooth module instead.)

The Neo Air comes disassembled, you will need to solder on the input-output header pins.

The Acrylic case screws together easily, and well done FriendlyArm for including five of each of the screws and posts, even though only four are needed. Losing an important screw can be very frustrating.

Setting up the Operating System

Once your Air is assembled, you need to connect a serial adapter for first boot setup. The only text editor installed out of the box is 'vi' so it's time to either learn vi, or edit your files elsewhere and paste the contents in.

You can use either a USB-to-serial cable or a Bluetooth-to-serial module.

Here's what you need to do.

  1. Connect to the serial console from another computer over USB or Bluetooth
    • On Mac do cu -l /dev/tty.HC-06-DevB (or whatever name your interface device is given)
    • On Linux do cu -l /dev/ttyUSB0 (Press the RETURN TILDE and PERIOD keys in sequence to exit cu)
    • On windows use Hyperterminal or other terminal software
  2. Log in as root (password 'fa') and change the passwords for 'root' and 'fa' accounts immediately.
    • # passwd root
    • # passwd fa
  3. Edit the system hostname (vi /etc/hostname)
  4. Configure the wifi
    • Get the example configuration file from the FriendlyARM Wiki
    • Edit the file on your Air: vi /etc/wpa_supplicant/wpa_supplicant.conf
  5. Reboot
  6. Login as root with your new password
  7. Update software and add some essentials
    • apt-get update
    • apt-get upgrade
    • apt-get install avahi-daemon avahi-utils man-db nano
  8. Reboot again
  9. Now you should be able to ssh to your Air using the name you gave it, eg ssh scampi.local
For those who can't use vi: If you don't know how to use the vi editor, you can paste in your files using cat, for example
  1. cat > /etc/wpa_supplicant/wpa_supplicant.conf
  2. Paste in your complete file
  3. Press CTRL-D to signify end-of-file
  4. Type cat /etc/wpa_supplicant/wpa_supplicant.conf to confirm correct content

Customising the hardware

I customised my Air like so:

  • I drilled a 6.35mm mounting hole for the antenna in the acrylic cover
  • I added a USB-A socket from my junk box (such as this component)

FullSizeRender 2

First impressions in use

The pre-installed Ubuntu installation looks a little strange (including only busybox's vi emulator as an editor is fine for an old hand like me, but a little rude to newcomers), I will be looking at switching to Armbian soon. The Armbian distribution for this board has just reached beta-test stage in the last few days; I previously booted the Armbian alpha-test version from SD card and it worked well, though I didn't yet test WiFi.

Power consumption is good, the board has been running from a single lithium battery throughout all the testing I have done.

The lack of on-board type A ports means I wouldn't recommend this board for use as a security camera hub, I would look at the Orange Pi Zero as an alternative here.

Looks ideal for robotic applications, especially connecting one or more Arduinos running Firmata via one or more of the three serial ports.

Next Steps

In upcoming articles I'll be looking at how to manage your IoT devices in a way that reduces risk to you and others in case of vulnerable or rogue devices. Rather than relying on the manufacturer's poorly supported cloud services to control to devices, I'll show how to use Node-RED and other tools to create a secure IoT installation.


Thursday, 20 October 2016

Making a custom breadboard for the Wemos D1 Mini.


The Wemos D1 mini is a great development board for the ESP8266 Wifi microcontroller. (For more details, see my post IoT for Absolute Beginners). The main drawback of the D1 Mini over other development boards is that it comes with the pins separate and you must solder them in yourself.

Once you've done this you will need a breadboard on which to mount your module. The D1 Mini is relatively wide, and only leaves
one column usable on the common 5-column breadboards. A better solution is to use two separate breadboards spaced
the correct distance apart.

You can do this with the small breadboards designed to mount on a lego-like base-board.
(But note, this board while it resembles Lego has a smaller bump pitch, and does not work with Lego bricks).

You can find links to a supplier of the parts on this post.

breadboards

Breadboard sled for WeMos D1 mini

Breadboard sled for WeMos D1 mini

I have designed and made this custom baseboard on a CNC mill. You will need two of the 5x11 breadboards, and this gives you four usable columns instead of one.

I made my sled by milling the outline with a 2mm endmill, drilling the locating holes with a 4mm drill, and drilling the corner fixing holes with a 3mm drill.
The G-code and OpenSCAD files are here.

If you use my G-code, you will need to start out with a 2mm endmill, then change to a 4mm drill then a 3mm drill at the tool change points.

If you use the OpenSCAD file, you can import it into your CNC software and cut the whole board with one tool.

Breadboard sled in OpenSCAD

If you don't have a CNC mill, you can simply use a saw and drill press or hand drill:

  1. Cut a piece of board 60mm x 40mm. I used white acrylic.
  2. Drill 4mm dia holes spaced 10mm apart vertically, and 32.5mm apart horizontally. That is each breadboard needs two holes 10mm apart, and the pairs of holes are placed 32.5mm apart measuring center-to-center.
  3. Drill 3mm mounting holes in the corners of your board (or to suit however you want to mount it)

Saturday, 24 September 2016

Using an ST7735 LCD screen with NodeMCU

On a previous post Somchai asked how to hook up an ST7735 LCD screen to his WeMos D1 Mini and use it with the NodeMCU firmware.

The NodeMCU platform (and compatibles like the WeMos) are a great way to get started in the Internet of Things.

See my Introductory Article for how to get started in IoT with NodeMCU.

Here's how to connect and use this inexpensive LCD screen:.

Connecting an ST7735 LCD to NodeMCU

From your du Pont cable set peel off nine male-to-female cables, I suggest brown,red,orange,yellow,green,blue,purple,white,brown (these are contiguous in my set).

Connect like this at the screen:

  • brown to GND
  • Red to VCC
  • Blue to RESET
  • Purple to A0
  • Yellow to SDA
  • Orange to SCK
  • Green to CS
  • White to LED+
  • Grey to LED-

Connecting an ST7735 LCD to NodeMCU

At the NodeMCU connect like this:

  • Brown to GND
  • Red to 3V3
  • Blue to D0
  • Purple to D4
  • Yellow to D7
  • Orange to D5
  • Green to D8
  • White to 3V3
  • Grey to GND

Connecting an ST7735 LCD to NodeMCU

Building your firmware

Using the NodeMCU cloud build service I made a firmware image that contained the modules I needed:

building nodeMCU firwmare for LCD

I installed it using esptool:

chris$ esptool.py --port /dev/tty.nodemcu-DevB write_flash -fs 32m 0x00000 nodemcu-master-17-modules-2016-09-23-22-47-56-float.bin
esptool.py v1.1
Connecting...
Running Cesanta flasher stub...
Flash params set to 0x0040
Writing 520192 @ 0x0... 520192 (100 %)
Wrote 520192 bytes at 0x0 in 59.1 seconds (70.4 kbit/s)...
Leaving...

And when booted it shows the modules present. You must have SPI, ucg and bit modules, the others are up to you.

NodeMCU custom build by frightanic.com
 branch: master
 commit: 8e48483c825dea9c12b37a4db3d034fccbcba0bf
 SSL: true
 modules: bit,cjson,file,gpio,http,mqtt,net,node,pwm,rtcmem,rtctime,spi,tmr,uart,ucg,wifi,ws2812
 build  built on: 2016-09-23 22:46
 powered by Lua 5.1.4 on SDK 1.5.4.1(39cb9a32)

Testing your screen

To test your screen, upload all the files from the NodeMCU ucglib example directory. You can use the GUI ESPlorer tool or the command-line NodeMCU-uploader tool to copy the files.

chris$ nodemcu-uploader --port /dev/tty.nodemcu-DevB upload *
opening port /dev/tty.nodemcu-DevB with 115200 baud
Preparing esp for transfer.
Transferring GT_box.lua as GT_box.lua
Transferring GT_clip.lua as GT_clip.lua
Transferring GT_color_test.lua as GT_color_test.lua
Transferring GT_cross.lua as GT_cross.lua
Transferring GT_fonts.lua as GT_fonts.lua
Transferring GT_gradient.lua as GT_gradient.lua
Transferring GT_graphics_test.lua as GT_graphics_test.lua
Transferring GT_pixel_and_lines.lua as GT_pixel_and_lines.lua
Transferring GT_text.lua as GT_text.lua
Transferring GT_triangle.lua as GT_triangle.lua
Transferring GraphicsTest.lua as GraphicsTest.lua
Transferring HelloWorld.lua as HelloWorld.lua
Transferring UcgLogo.lua as UcgLogo.lua
All done!

Then run the demo by typing dofile("GraphicsTest.lua"), or using the GUI or the CLI to invoke it

chris$ nodemcu-uploader --port /dev/tty.nodemcu-DevB file do GraphicsTest.lua
opening port /dev/tty.nodemcu-DevB with 115200 baud
Executing GraphicsTest.lua
dofile("GraphicsTest.lua")

It happens that the GraphicsTest.lua file defaults to using using the ST7735 screen. If you have a different supported screen, make sure that you select that screen when you build your firmware, and that you edit GraphicsTest.lua to call the setup routine for your screen.

Connecting a WeMos D1 Mini

If you have a WeMos D1 Mini, the connections are the same:

Connecting an ST7735 LCD to a WeMos D1 Mini

Using the screen in your own code

In your own code, I've found you can connect blue (reset) to the NodeMCU reset and save a pin.

My setup routine looks like this:

-- setup SPI and connect display
function screen_init()
    -- Hardware SPI CLK  = GPIO14 = D5 orange
    -- Hardware SPI MISO = GPIO12 = D6 (not used)
    -- Hardware SPI MOSI = GPIO13 = D7 yellow
    -- CS, D/C, and RES can be assigned freely to available GPIOs
    local cs  = 8 -- GPIO15 = D8 green (pull-down 10k to GND)
    local dc  = 4 -- GPIO2  = D4 purple
    -- local res = NC -- RST (blue)


    spi.setup(1, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, 8, 8)

    -- initialize the matching driver for your display
    -- see app/include/ucg_config.h
    --disp = ucg.ili9341_18x240x320_hw_spi(cs, dc, res)
    disp = ucg.st7735_18x128x160_hw_spi(cs, dc)

    disp:begin(ucg.FONT_MODE_TRANSPARENT)
    disp:clearScreen()
    disp:setColor(255, 255, 255)
    disp:setColor(1, 255, 0,0)
end

Monday, 12 September 2016

Program Arduino and ESP 8266 projects over Bluetooth from Mac

This article explains how to use a Bluetooth-to-Serial module to allow you to work with the Arduino and ESP8266 microcontrollers without needing a direct USB connection.

Using Bluetooth saves a lot of wear and tear on your USB ports, and eliminates the risk of damaging your computer if you make a wiring mistake.

hc06_in_use

Above: The NodeMCU ESP8266 development board (right) connected to a HC-06 bluetooth module (left)

In a previous article I talked about getting started with the NodeMCU platform, which is a programming environment for the ESP8266 WiFi microcontroller.

If you use the "NodeMCU Development Kit" reference board, you get the ESP8266 module itself, plus a USB interface that you can use to power the board, and also to download your code to it. The popular Arduino physical computing platform also has built in USB.

However if, like me, you use an ultralight laptop computer with a limited number of USB ports, it might be more convenient to use a Bluetooth interface to download code from your PC. This also has the advantage that there is literally no way that any mistake you make in your experimental circuits could damage your PC.

The ESP8266 doesn't have Bluetooth built in, but it is easy to add Bluetooth by using a Bluetooth-to-serial module. The "HC-06" module is available for about $4 from many vendors, such as here.

This module acts as a bluetooth character device, and once you have paired with it, you can use it just like any other serial port, using the same tools you would use to download your programs over USB.


Setting up your device


You can think of the HC-06 module as a dual interface bridging device. Anything received wireslessly on the Bluetooth side is transmitted as asynchronous serial via the wired interface. Anything received on the wired serial side is transmitted via the wireless bluetooth interface. Once the device is connected it is "transparent", that is the device simply relays whatever it receives without changing it.

Out of the box the HC-06 module answers to the name 'linvor', and operates at 9600 bits per second (bps). Arduino and ESP8266 typically work at 115200 bps, so we need to reprogram the HC-06 to work at this speed. To do this, we must connect to the serial interface on the HC-06 and send some commands.

If your application works at 9600, and you are happy with the default device name, you can skip this section.

To reprogram the HC-06 you will need a 5-volt serial port. The easiest way to get this is to buy or borrow a USB-to-serial adapter. This module is one I prefer, as it is switchable between 5v and 3.3v for the serial signalling voltage. Mac users might prefer this device which uses a USB chip from FTDI, as I have found the drivers for this chip are well supported on Mac.

To program your device, use jumper cables to wire like so:

  • 5v on HC-06 connects to 5v on USB adapter
  • Ground on HC-06 connects to ground on USB adapter
  • Transmit (TX) on HC-06 connects to Receive (RX) on USB adapter
  • Receive (RX) on HC-06 connects to Transmit (TX) on USB adapter

Note that transmit and receive are "crossed over". If you think about it, it makes sense, whatever the USB adapter transmits, the bluetooth module must recieve.

hc06_connection

Above: Wiring a USB-to-serial adapter for initial programming of a HC-06 Bluetooth adapter

Once you have the physical connections made, it's time to connect to a PC and use a Serial Terminal program. If you have Windows, use Hyper Terminal, if you have Linux or Mac use "/usr/bin/cu".

Note: The HC-06 module has a quirk, you must send an entire command in under around half a second, or the module will ignore the command. Don't try to type the commands, prepare them in a text editor, then paste each command into the terminal window one by one.

We are going to send three commands to the HC-06

  • AT+VERSION - Request the device to report its version. We do this only to confirm that the connection works.
  • AT+NAME=nodemcu2 - Give the HC-06 device a name. I have chosen to name it "nodemcu2" (because I have another HC-06 that I named "nodemcu")
  • AT+BAUD8 - Set the serial data rate to 115200 bps

The HC-06 understands a limited number of "AT commands" which is a command scheme commonly used by analog modems. See this article if you want to know more about the commands that the module understands.

To begin, we connect to the USB-serial adapter by running a program called 'cu' (which stands for 'Call Up' as it was originally used with serial-connected analog modems). On Linux this is as below. On Mac it will be /dev/tty.something depending on the model of USB adapter you have.

cu -l /dev/ttyUSB0 -s 9600

Once you are connected, paste in the below commands one at a time. You will not see the text that you paste on screen, but you should see answers to the commands as shown in the screenshot below.

To exit the cu program you must press the return, tilde (~) and period (.) keys in succession.

Once you have completed the reprogramming, disconnect, and reconnect using 115200 bps. To test that the device is now working at 115200 bps, paste the version command again. You are now ready to pair the device, and are finished with the USB-to-serial adapter.

AT+VERSION

AT+NAME=nodemcu

AT+BAUD8

hc06_configured

Above: configuring a HC-06 adapter by pasting commands into a terminal window

Troubleshooting your USB adapter

If you cannot get the HC-06 to answer, confirm that your USB adapter is working. By connecting its transmit pin back to its own receive pin, you create a "loop back" situation, where anything the USB converter transmits, it also receives.

Connect to the device and type some text. You should see it appear on screen. If you disconnect the wire and type some more, text should not appear.

usb_serial_loopback

Above: testing a USB-to-serial adapter in loop-back arrangement

Pairing your HC-06

In order to have your computer present the HC-06 as a usable device, you must "Pair" the device using your computer's bluetooth settings. This is a one-time operation. You can pair an HC-06 with several computers if you need to.

On a Mac, open the System Preferences app and select the bluetooth panel. Look for your HC-06 to appear in the "available devices" pane, and select "pair".

bluetooth_discovery

Above: MacOs is searching for Bluetooth devices available to be paired. Here we have two devices already paired, and have discovered two unpaired devices.

Note that the pairing will fail initially, because your Mac does not know the PIN for the HC-06. The default pin for HC-06 is "1234". Select "Options" and enter the correct PIN.

bluetooth_pairing_failed

Above: Initial pairing of a HC-86 will fail to complete as MacOS does not know the pairing code. Click 'options' to enter the code

bluetooth_pairing_code

Above: Entering the pairing code for a HC-06 module. The default code is '1234' (which is the same code I have on my luggage).

Once your device is paired, it will appear as a file in the /dev/directory, eg. my device is /dev/tty.nodemcu2-DevB.

bluetooth_pairing_complete

Above: Successful pairing of a HC-06 bluetooth module.

On Linux or Windows your bluetooth device will be /dev/ttySomething or COMsomething: respectively.

Using the HC-06 to communicate with serial devices

Now that you have a paired HC-06 you can connect to it like you would any other serial port (such as the USB-to-serial adapter we used above).

cu -l /dev/tty.nodemcu-DevB -s 115200

When using an IDE to interact with NodeMCU devices, your bluetooth serial port should now appear in the menu of available serial ports.

ESPlorer-bluetooth

Above: Selecting the HC-06 bluetooth adapter in the ESPlorer IDE software

Thursday, 8 September 2016

IoT for absolute beginners - Part 1

Getting started in the Internet of Things (IoT) with the NodeMCU platform


If you have been wanting to get into the Internet of Things (IoT) but are not sure where to start, or you are enthusiastic about IoT and want to bring others into the field, I am going to describe how to get started with some easy-to-use hardware and software for as little as $20.

slacker_toast
Above: a sophisticated IoT project still using only 4 components costing under $20.

This article is is targeted at those who have some knowledge of computer programming (at least that it exists) but little or no experience with digital electronics. I aim to introduce you to the tools that you will need and allow you to get started experimenting with The Internet Of Things.

If you are interested in conducting a group "Hackathon" at work or
school, this should be all you need to get your teams started.

If you're a corporation looking to conduct a team building
hackathon consult me.


The basics of IoT platforms


You're probably reading this on a computer that consists of a central processor, some memory chips, some file storage (magnetic drive or more memory chips), a keyboard or touch-panel, and an LCD screen. These items are the basics of all computing: processing, volatile (temporary) storage, nonvolatile storage, input devices and output devices.

IoT devices are just the same, except everything is much smaller; they are typically powered by a microcontroller which is a term for devices that combine all the traditional parts of a computer onto a single chip (or an integrated multi-chip module).

Just how small can vary. The range of scale and power available for IoT devices encompasses:

  1. 8-bit microcontroller devices (such as the well known Arduino family), size around 5cm, costing under $5
  2. 32-bit microcontroller devices, size around 5-10cm, costing
    under $10
  3. Small form-factor PCs (such as Raspberry Pi, and various similar devices), size under 10cm, costing under $100

I am going to talk about the middle class of 32-bit microcontroller devices in this article. At the low-end, the Arduino and similar are excellent but are not powerful enough to connect to the internet on their own. At the high end, there's a place for the more powerful and expensive devices, but I'll talk about how I use those boards another time.

In the microcontroller realm you typically have the following resources:

  • For processing you have a processor that runs between 1 and 100 million instructions per second (MIPS).
  • For memory, you typically have a frustratingly small amount of RAM, from 1kB to a few hundred kB.
  • For file storage, you have somewhere from 8k to a few megabytes of FLASH memory.
  • For input and output you have from two to twenty digital "pins", and some communication interfaces such as Asynchronous serial, Inter-IC communications Bus (I2C), Bluetooth, or WiFi. Under the control of your programs, the IO pins can be used singly or in groups to control buttons, lights, sensors and screens.


microcontrollers
Above: Classes of embedded computers: L-R DigiSpark, Arduino Nano, NodeMCU, Raspberry Pi

A modern 32-bit microcontroller is about as powerful as a home computer from the 1990s, but shrunk to the size of a postage stamp.

These devices can be programmed in assembly language or low-level languages such as C and C++, but I won't go into those here. Beginners will be much more comfortable with higher-level languages such as Lua and Python.

To develop program code for a microcontroller you write your programs on a normal sized computer and then "upload" the program to the microcontroller. This can be done with a wired connection or sometimes over wireless links.

For the rest of this article I am going to talk about one particular combination of hardware and software that I think makes an economical and beginner-friendly platform for IoT experimentation, the NodeMCU platform.


The hardware - Espressif ESP8266 Wifi Modules


The ESP8266 is a tiny microcontroller chip invented by Espressif in China. It is intended for very low cost smart devices such as internet controlled light bulbs and power switches. There are a number of "compute modules" that combine the ESP8266 chip with some flash memory and power components to provide a postage-stamp-sized module that can be incorporated into larger circuits. Sometimes these modules are then mounted on a carrier board which adds more power circuitry and some switches. One of the most beginner-friendly is the reference design from the NodeMCU project. The "NodeMCU Developers Kit" (DevKit) is an open-source design that is available from a number of manufacturers for under $5 (more about this below).

esp8266

Above: Two different ESP modules (left) and a NodeMCU DevKit board consisting of module plus extra circuitry (right)


The software - NodeMCU


The NodeMCU project provides a firmware distribution for the ESP8266 modules. The term "firmware" is used to describe software that you program into hardware just once (get it? It's in between hardware and software. Engineers didn't get out much before computers became cool). You can think of the NodeMCU firmware as a very simple operating system for the module environment; you combine the standard firmware with your custom-written application software to solve some particular problem.

The NodeMCU firmware is written in C, but provides an environment for you to upload and run application programs written in Lua (an easy to learn scripting language). So all the hard C programming has been done, meaning you (the beginning IoT programmer) can work in the much more friendly Lua language. To use NodeMCU, you must install the NodeMCU firmware on your device just once, after that you can simply uload programs written in Lua into the device's flash memory over a USB cable, to make the device do whatever is desired.

The NodeMCU project also provides the reference hardware design for their Development Kit board, which is ideal for running the firmware, but the firmware itself will run on almost any ESP8266 module, not just the ones based on the reference design.

The WeMos D1 and D1 Mini boards are another design that is ideal for use with NodeMCU.

The NodeMCU development kit board gives you around 10 general purpose IO pins, WiFi wireless ethernet, asynchronous serial port, plus a USB socket for power and for uploading software to the device. Other ESP8266 modules may have more or fewer IO pins. You can add bluetooth if desired by connecting a bluetooth module to the asynchronous serial pins. You can also store files in whatever whatever space in your module's flash memory is left-over after the firmware and your application software are uploaded. The NodeMCU DevKit board has 4MB of flash memory, of which around 3MB remains available after installing the firmware.

The NodeMCU DevKit board has a blue light-emitting-diode (LED) connected to pin D4, and a push button (labelled "Flash") connected to pin D3, so if you want to dip your toe into IoT for the least amount of money, you could buy the DevKit board and nothing else, powering it by USB cable from your computer or from a spare USB charger.

IoT in a Mint Tin
Above: The NodeMCU DevKit reference design is small enough to fit into the lid of a mint tin, but powerful enough to connect to the Internet.


Writing and uploading code


NodeMCU has some example code on their website, and there is a comprehensive documentation site for the NodeMCU Lua programming environment. I'll be posting my example projects here soon, also.

There are a number of software IDEs (Integrated Development Environments) available for editing and uploading Lua code. The quality of IDEs in the embedded world might be a little less than for mainstream computers, however I have found the ESPlorer application is serviceable, if a little quirky. It's compatible with Mac, Windows and Linux.

Most ESP modules ship with a firmware that is intended to work as a "WiFi Modem" (the so-called AT Firmware). The first thing you'll need to do is wipe this and install the NodeMCU firmware by following these instructions.

You can obtain the latest NodeMCU firmware from this service. I recommend you start with the default modules plus HTTP, I2C, MQTT, PWM and SPI. If you buy an LCD screen add the UCG module.

Once your board is running the NodeMCU firmware, there are three main ways to get your Lua application program code onto your module:

  1. Use a USB-to-Serial converter between your PC's USB port and the NodeMCU board's asynchronous serial interface. The NodeMCU DevKit has a built-in USB converter, so you just need a USB cable.
  2. Connect a Bluetooth-to-Serial module to the NodeMCU board's asynchronous serial interface, and pair the bluetooth module with your PC.
  3. Use one of the above methods to install a program on your board that lets you send further programs to it over WiFi.


We'll cover the first two of these methods in the next article in this series. From the point of view of your PC, they are the same, except that in the first case you are connecting to a virtual serial port implemented by the USB converter, and in the second case you are connecting to a virtual serial port implemented by the bluetooth module. USB is slightly cheaper and easier to work with, but do consider Bluetooth if you have a Mac, especially those with limited USB type-A ports.


Connecting your module to the outside world


The NodeMCU programming environment provides a number of library functions grouped into modules, and has programming modules that provide high level abstractions for many common input and output devices. Where there is no high level abstraction, the low level GPIO module provides direct access to the input output pins and allows youto write your own programs to interface with almost anything.


The NodeMCU firmware provides a number of core software modules to perform various tasks (such as read particular models of sensors, and control particular models of display), and there are even more modules availble as open source contributions that you can add to your base firmware. There are web services that will construct a new firmware image for you containing the set of modules that you select, or you may upload the NodeMCU source code, import some extra modules, and compile a firmware image that contains all the modules you desire.


The bare basics of digital electronics


Computers do all their thinking with binary logic (ones and zeros), and represent binary logic in the physical world using voltage. A logical one is high voltage, a logical zero is no voltage. When a computer talks to another computer or a peripheral device, there's one or more wires which are either at high voltage or low voltage. That's basically all there is to it. Skip the rest of this section if you like.


For a long time, most computers used 5 Volts as the standard high voltage. As computers became faster and used more power, the industry shifted toward 3.3 Volts as the standard voltage.


The compute-modules we will be using follow the 3.3 Volt convention, but you should be aware that a lot of stuff still uses 5 Volts, and some 3.3 Volt equipment will be damaged (possibly fried) if given 5 Volts where it expects 3.3 Volts. The ESP chips are claimed to be "5 Volt Tolerant" but there have been reports of chips failing when exposed to 5 Volts, so lets stick to 3.3 volt devices in our projects. There are inexpensive conversion circuits that you can use where you need to connect 5 Volt signals to devices that may be harmed by voltages above 3.3 Volts


Solderless breadboading and peripheral modules


Commercial electronic devices are made of components joined together using solder, which is an alloy of various metals that has the particular quality of melting at a relatively low temperature (around 200 degrees). (Don't panic, you will not need to do this.) In soldered circuits, components are placed in contact with other components, wires, or flat panel "circuit boards", and then joined permanently by flowing molten solder onto each electrical connection using a hand-held soldering iron or more complex tools. Once the molten solder cools and solidifies, components are permanently joined.


The prospect of using molten metal to construct circuits is a bit daunting for beginners, so the good news is you can get a very long way indeed without needing to do any soldering. The projects I teach can be built without any use of a soldering-iron. Soldering is an inexpensive, compact and robust way to permanently connect components, and should be considered once you have your design perfected and want to make lots of a particular circuit, but to start out we will use other techniques. The trade-off is that the things we make will be a little bit larger, and more delicate (they might come apart if you drop them).


To make relatively reliable but inexpensive projects, we will use these tools:

Solder-less breadboards.
These boards have rows of spring-loaded sockets that are connected together electrically. A wire placed in a socket will be connected to the other sockets in the same row.
Jumper-wires
We'll use inexpensive pre-cut lengths of wire fitted at each end with either metal pins suitable for plugging into breadboards, or with sockets suitable for accepting pins. You can even cut your own jumpers from a roll if you use the right kind of wire.
Peripheral modules
We will interface our compute module to various kinds of Peripheral Input/Output (IO) modules, beginning with a starter kit of handy modules


breadboards

Above: various types of solderless breadboards, the smallest are repositionable on a Lego-like baseboard. Each socket is electrically connected to the other four sockets in the same row of five.


jumpers

Above: Jumper wires for inter-connecting non-adjacent sockets, and for connecting to off-board modules


modules

Above: Several kinds of peripheral input and output modules



Imagine the most cliched 1960s computer (as seen in old movies) that you can, the above techniques of modules and interconnecting wires are exactly the technologies that began the computer revolution. To recap, we will have a compute module, installed on a breadboard, and connected by jumper-wires to peripheral modules which might be on the same breadboard, on an adjacent board, or mounted on a panel.


A 1960s computer from IBM, showing how early computers used modules wired together.

Above: Mid-1960s IBM computer component showing panel-mounted I/O and plug-board wiring.


nodemcu

Above: NodeMCU DevKit board mounted on a solderless breadboard and connected to module consisting of three full-colour Light Emitting Diodes. On these breadboards, each socket is electrically connected to the other four sockets in its row.


Simple outputs (e.g. for Lights)


To control lights, or motor modules the gpio firmware-module can be used to set a pin to a high or low voltage using the gpio.write function. The pins on the ESP and most microcontrollers can act as either inputs ("reading" the voltage presented to the pin) or outputs ("writing" a voltage to the pin). We must set the mode of a pin with the gpio.mode function to use it as an output.

Microcontrollers don't output very much power on their IO pins, typically only just enough to light up a small light-emitting-diode (LED), so if you are controlling higher powered devices like relays or motors, you will need to use a power boosting circuit. Generally modules for relays and motors include this boost circuit so can be connected directly to your output pins.

When you use a light-emitting diode (LED) you generally need another component called a 'resistor' to set the brightness by limiting how much power may pass through the LED. Without a resistor the LED may consume too much power and burn-out. Pre-built LED modules will often include all the extra power-limiting circuitry you
need.


led_module
Above: A Light-Emitting Diode (LED) module connected so that it can light up red or green under control of the NodeMCU DevKit


Simple inputs (eg. for Buttons)


If you configure a pin as input by calling gpio.mode then it does not output any voltage, instead any voltage applied from outside will be reported as a logical one or a zero when gpio.read is called. When the NodeMCU environment starts up, all the pins are in input mode unless you reconfigure them in your code.

The simplest way to connect a switch is to have a switch between the pin and ground (zero volts) and to have other circuitry that presents high voltage when the switch is not pressed. The extra circuitry can be part of a switch module, or provided by the "internal pull up" circuit inside the microcontroller. Again, pre-built switch modules should include any extra circuitry that is needed.

A digital input pin is going to convert whatever voltage it sees into one of two values. Typically anything from 0 Volts up to about half of the high level will read as a zero, and anything higher than that will read as a one. Some microcontrollers can read "analog" voltage where the actual voltage is reported as a number proportional to the voltage (say converting a voltage between zero and 3.3 volts into a number between 0 and 255). We'll stick to digital inputs only here.


button_module
Above: A button module connected to a NodeMCU DevKit


Internet access


Once we have a Thing with buttons and lights, we are ready to join the Internet Of Things, typically via wireless ethernet (WiFi)

There are four modules in NodeMCU for talking to the Internet:

Wifi

For configuring the wifi hardware (as an access point, client, or both) and scanning and joining networks

Net

For making network connections or implementing servers

HTTP

For making HTTP requests or implementing servers

MQTT

For publishing messages to the Message Queue Telemetry Transport, or subscribing to topics on a message server


Screens and more


So far we have discussed only the simplest input and output, switches and lights are from the point-of-view of a microcontroller communicating only a single binary digit --- one 'bit' --- of information, something is either on or off. More complex information can be communicated in two ways: by using multiple pins, or by using one pin (or a few pins) as a serial communication bus.

There are a couple of different ways of making a serial bus, from most to least complex these are:

  • USB (Universal Serial Bus) is very popular but generally too complicated for most micro-controllers and modules
  • TTL Serial (Asynchronous serial link) is an ancient protocol once commonly used for modems and printers, and still used to program many microcontrollers
  • I2C (Inter Integrated-Circuit bus) uses two pins (a clock and a bi-directional data pin). This is often used to talk to sensors and simple displays.
  • SPI (serial peripheral interface) uses one pin in each direction plus some clock signaling and device identification pins. It's often used to talk to graphical display modules, sensors and memory cards.
  • OWB (One-wire bus) uses a single pin that acts as clock and bi-directional data; it's slow but cheap. A popular temperature sensor is the best known use.
  • Various simple proprietary signalling mechanisms

Most microcontrollers have hardware and software to communicate with several of these technologies. As long as you know which protocol a particular device module expects, you should be able to talk to it.

The good news is that the NodeMCU programming environment has built in firmware modules to talk to many different kinds of serial IO devices such as sensors, addressable strings of LEDs, and various kinds of displays. It also has lower level modules for each kind of serial bus, so that if you have a hardware module that is not directly supported you can write your own interfacing code.

As an example, one could construct an adjustable thermostat consisting of a temperature and humidity sensor, a graphical liquid crystal display, a rotary dial switch and a push-button switch entirely using off-the-shelf modules supplied as part of the NodeMCU environment.

toast_flat Above: A sophisticated but easy to assemble IoT project consisting of a rotary dial switch, an LCD Screen, and an InfraRed proximity detector.

See Ideas below for some more project examples.

Shopping lists

Here is what to buy to get started. I will present three lists - A basic starter set, a comprehensive but inexpensive set of modules, and some stretch options.

As I mentioned above, for the very budget-conscious, you can buy just the NodeMCU DevKit board itself and experiment with its on-board button and LED.

The item listings below are at AliExpress.com which is a Chinese electronics and consumer goods bazaar. Sometimes items go out of stock or change price unexpectedly, I'm happy to advise if you are unsure about anything.

Basic starter set

The bare minimum starter kit currently costs around US$12 if you order the recommended items below (I have no commercial interest in these recommendations):

NodeMCU development board- $3.18
CPU with wifi and USB interface. This has one light and one button built in.
A 400-hole breadboard- $1.00
This breadboard will accomodate your NodeMCU board and leave space for plugging in other modules if you so desire
10cm Jumper wires- $1.55
A basic set of multi coloured jumper wires can be peeled apart singly, or in twos and threes, as needed.
Button module- $0.95
You probably want one or more buttons so that you can send messages to the internet. Look at the sensor kit in the next section for more input options
Light-emitting-diode (LED) module- $0.70
This module actually has three LEDs - one red, one green, one blue, in the same package. You can use just one colour, or mix colours.
A USB battery - $3.91
A rechargeable power bank is the best way to power your projects. An old phone charger works too. Consider buying locally as some countries will not accept batteries by airmail. If you don't already have a micro-USB cable, they cost around one dollar.


Internet of Things (IoT) starter kit
Above: all the items in the $12 basic IoT starter kit.


If you are buying for a team hackathon, consider searching for the same item plus "10pcs" or "100pcs" you will often find bulk items at an even lower cost.



A comprehensive set of Input/Output modules


Once you have a basic kit, you might like to experiment with things other than buttons and lights. A kit containing one each of practically every kind of sensor costs a little over US$10.00:

A selection of input/output modules- $10.74


sensorkit

Above: A $10 sample-bag of peripheral input and output modules



So for around $20 total outlay you can be up and running with the ability to build many kinds of IoT projects.


Special extras


You might like to consider these optional extras:


Bluetooth-to-serial interface - $2.78
If you find plugging and unplugging USB to be annoying, or have an ultralight notebook with limited USB, you can use Bluetooth to upload to your board. You will need to buy or borrow a USB-to-Serial converter, below, to set up this module. I'll cover how to use this module in another post.
USB-to-serial interface - $1.50
If you have trouble finding drivers for the USB chip built into your NodeMCU module, or if you are using an ESP board that lacks a built in USB interface, the FTDI USB-to-serial converter has the best supported drivers.
Longer jumper wires - $2.55
Jumper cables are commonly available in 10cm, 20cm or 30cm lengths. While the shorter ones are most useful, a set of longer cables is handy to have.

Shorter jumper wires - $1.68
If you need to join nearby rows on a breadboard, a short wire that is exactly the right length can be neater than a jumper cable
128x160 LCD Screen - $3.15
A small video screen lets you show text, graphics and menus. This screen uses the ST7735 chip that is supported by NodeMCU's ucg module.
320x240 LCD Touch screen - $7.62
A larger LCD screen with touch panel, which can take the place of a whole lot of buttons. This screen uses the ILI9341 chip that is supported by NodeMCU's ucg module.
Mini breadboards - $3.81 for 6
These small breadboards clip together or can be stuck to a surface. Handy for modules that are too wide for a single board.
Small breadboards and a baseboard - $3.55 and $2.82
These boards can be snapped onto a Lego-like baseboard (not Lego compatible) which lets you arrange them exactly how you need them


Enclosing your projects


Often a project sited on a breadboard or two needs no box. If you want to box it up, here are some suggestions:

  • Use plastic food containers from the supermarket
  • Pegboard and zipties
  • Buy project enclosures from your hardware store or AliExpress
  • Make custom enclosures if you have access to a CNC Mill or Laser cutter (try your local Makerspace)

enclosures Above: suggestions for enclosing your projects.

What can I build

Future articles will go into the practicality of of setting up your board, and some some example projects, but here are some possibilities for IoT in the home and workplace to get you thinking:

  • A doorbell that sends a notification to your phone wherever you are
  • A sensor that alerts you when the toaster has popped up
  • Measure the temperature outside, and in each individual room inside
  • Send a notification when an item is placed in the mailbox
  • Display real-time status of your projects or software builds with coloured lights
  • Display the time of the next booked meeting in a meeting room
  • Send an alert if it starts to rain
  • Report the occupancy of the visitor carparks in your building
  • Answer the question "Oh, no, did I forget to close the front door?"

temperature Above: temperature and humidity sensor built on a small breadboard. Settle once-and-for-all whether Jane's office is really colder than Bob's!

toastify Above: NodeMCU module wired up to modules for combined dial/push switch, infrared object sensor and a small LCD screen. This project sends you a reminder alert when your toast is ready.

wemos Above: Wemos D1 module with bluetooth-to-serial converter and an interface board for controlling an illuminated pushbutton switch. Intended as a "team meeting alarm".

Wednesday, 24 August 2016

The Thirty Second Photo Studio

Do you need to photograph a small item? Couldn't be bothered setting up a studio soft-box?

Try this:

  1. Load about:blank on your web browser
  2. Crank the screen brightness to maximum
  3. Place one sheet of blank paper over your keyboard
  4. Position your item
  5. Lower the screen to light the item
  6. Snap, you're done.




Friday, 22 July 2016

Hot-Glue on Roses and Zip-Ties on Kittens


Here are A Few of My Favourite Things that I do when I am building a
multi-component installation.

When I need to turn a prototype into a working installation, two
important tools in my toolbox are hot-melt glue, and self-locking
cable ties (also known as "Zip Ties").

Pegboard and Ziptie module layouts

Together these techniques help to turn a jumble of wires and parts into
a robust installation that will function reliably and look professional.


Custom patch cables and headers


While pre-made "du Pont" jumper leads are convenient and inexpensive,
sometimes you want an exact length. Jumper leads typically come in
10cm, 20cm or 30cm lenths, but when you're making a permanent
installation, you want your links to be the exact length you need, to
reduce clutter. Here is a technique I learned in the days of the MIT
"Handy Board" (an early robotics experimenters' platform, popular in
the early 1990s):

First, obtain a supply of snap-off headers, female header pins, and
ribbon cable. Old parallel-ATA data cables are good, or you can buy a
roll of coloured ribbon cable. You can also cut your existing du Pont
cables to length and attach new ends.

Next hold your headers in a soldering clamp, and tin each pin.
Strip and tin your wires. Solder the wires to the pins by holding
them overlapped by 2mm and touching with the soldering iron.


Making a custom patch cable

Making a custom patch cable


Now you need to insulate the joins. Heat-shrink is good, but
fiddly. A quicker and more robust way is HOT GLUE. Heat up your glue
gun and apply a small amount of glue to completely cover all the
wires. Build the glue up onto the body of the header. Don't be
tempted to touch until it is cool.


Making a custom patch cable

Making a custom patch cable

Making a custom patch cable



Odd-sized headers


If you need a 14 pin header or any uncommon size that you don't have
as a one-piece header, reach into the supply of headers that you
do have.

You can either:

  • Remove one pin from a large header, and then cut the header at the
    missing pin to make smaller header, or
  • Hot-glue two or more smaller headers together to make a single
    large one


"SIL Gadgets"


"SIL" is an acronym for Single-In-Line, and refers to the arrangement of connection pins in single row, which is best for working with solderless breadboards and/or Arduino.

If you are working with breadboards, make up a number of cables that join a male header to various components such as switches, LEDs, speakers and batteries. When you want to test a module it's handy to have pre-wired inputs and outputs that you can re-use for temporary hook-ups.
I have a boxful of these that I've made for various devices, and some of them have been reused over and over for many years.


Examples of custom headers made with hot-glue

A library of "SIL gadgets" for breadboard experiments


Pegboard lash-up installations


When your installation consists of a number of modules connected by jumper cables, an excellent way to make the lash-up installable is to cut a piece of peg-board to size and fix each module in place with cable-ties.
Don't forget, the self-adhesive backing on most breadboards is there to be used, too.

I use this pegboard technique for home automation equipment points, and for larger robots.


Raspberry Pi and Arduino door lock

Motion sensing contoroller for LED string lights

Robot drive platform from dead vacuum bot

Minature K9 Robot Chassis