NEO2 NAS Part Two

NAS BoxI’ve separated this off as it has gained a life of it’s own. When I originally opened up the NAS box from FriendlyArm and plugged in my NEO2 (same company) I’d just planned on trying out the free NAS software. Little did I know how far this would develop…

it occurred to me as I was wondering why on earth I needed a NAS without RAID in the first place, that this is a nice box with a nice power supply for a NEO2 and disk (I have the version of the box for the original NEO so a little filing of the ETHERNET opening was necessary – no big deal)…

The Disk:

So I put my SD with FriendlyArm’s Ubuntu  into the NEO2 – along with my script for Node-Red etc etc, all set up and plugged in.  As you might expect it started as normal so I went in to see if SDA (the hard disk) appeared.

Sure enough – along with SDA1 – so off I went to the web and found out how to use FDISK  - deleted the partition, created a new one,  made a directory in my PI directory and MOUNTed the disk. More on that later.

Well, I have to say that worked swimmingly well, so next using WinSCP I tried copying a 3.8GB file across. It copied flawlessly at 35MB/second!

So a couple of things – I’ve just finished my solar installation and I just happen to have 12v available from it – with lots of power to spare – I figured it made sense to plug this box in – ok, the network can still go down but there is NO chance of the 12v failing.

Of course you can’t access the GPIO pins via their connectors but the back is available so with a soldering iron I figured if need be I should be able to access a few of them given that there are schematics on the FriendlyArm site for just about everything  so it would be no problem to out which ones are still free.

So I ended up with a disk (available via Samba once I remember how) and a nice sturdy box for my NEO2 and disk. As the NEO2 also has an audio in and out – it would be no problem with a drill to add a 3.5mm jack on the front panel. If I could think of a decent small socket for the job I’d bring the UARTs out too – remember – there are four of them – that back panel is sitting doing nothing…

NEO2The next step was to allow the NEO2 to use the hard disk properly – i.e. instead of the SD.  I’d already done a mount and tested a file transfer and achieved 38MB/s on a large (3GB) file – so I was happy to try.

The instructions are somewhat different to a Raspberry Pi due to this little machine not having a cmdline.txt file.

If you've used my script – absolutely make sure LOG2RAM is NOT running before doing this... best install without Log2ram. If Apache loses it's log file in the setup, it won't run - and that happened to me (mind you that is easily fixed).

Alternatively, if you already have it installed,  disable log2ram (which is in my script for all my machines now but isn’t needed when using  a hard drive).

sudo systemctl disable log2ram

then  go to /etc/cron.hourly and delete the log2ram file – and reboot.

So the basic idea is to make a folder and point the hard disk to it – mount it – then copy almost everything to the hard disk… then change the settings in the boot folder to use the hard disk.

In this case – no changes to fstab – but one simple change to a file in the boot directory (boot.cmd) and having made the change you then you have to run a command to create a new boot.scr  - this is not what you’d see for a Raspberry Pi.

This is what I did:

Assuming a hard disk on /dev/sda and assuming for now being logged in as ROOT to ensure there are no issues with privilages…

I wiped any partitions in the drive (d, n, p, defaults then w for write) and created a new file system

fdisk /dev/sda
mkfs.ext4 /dev/sda1

I then rebooted. Some say you don’t need to – I found I did. I then made a directory called mnt (for want of something better), mounted the disk over that folder (which now means that folder is actually on the hard drive and not the SD – simple when you get used to it) and copied everything across  (excluding /boot and the /mnt directory itself)

mount /dev/sda1 /mnt
sudo rsync –ax   / /mnt

At first this all seems odd but becomes second nature very quickly. You could add a progress option in there but the whole thing takes only a minute or two and I didn’t want to slow things down. The -a option means "archive", which should preserve file permissions, modification times, etc., and the x option means "don't cross filesystem boundaries", so it'll skip /boot and /mnt

I then altered /boot/boot.cmd 2nd last line.. changing the reference to the SD to the new hard drive – see bold.

setenv bootargs console=tty1,115200 earlyprintk root=/dev/sda1 rootfstype=ext4 rw rootwait fsck.repair=${fsck.repair} panic=10 ${extra}

To make that work I had to run this line (again as root)…

mkimage -C none -A arm -T script -d boot.cmd boot.scr

So above, I’ve changed the boot setup firstly to get rid of serial debugging as the serial output on that NAS box is serial port 0 and I didn’t want debug on there – and secondly to change the normal pointed to the internal SD – to the new drive partition SDA1.

I rebooted…. and sure enough I was on the new file system – I knew that as previously I’d put a dummy file in my /home/pi directory after copying everything – and that file had now disappeared.

The terminal sign on message,on reboot, showed I was using 60% of RAM and 2% of the 111G hard drive.

A quick test of a file transfer from the PC to the NEO2 showed around 37MB/s transfer.

All that remained now was to use Samba to share a folder. I am assuming here that Samba is installed – it is on my script. In my PI user folder I made a folder called “share”. From here you can do this stuff as user Pi or ROOT but Pi need SUDO permissions for accessing some places.

I created a user PI for Samba…

sudo smbpasswd -a pi

I then went into /etc/samba/smb .conf to add information (thanks Antonio) to share a folder called /home/pi/share

[share]
comment= Sharing dir
path=/home/pi/share
browseable=Yes
writeable=Yes
only guest=no
create mask=0777
directory mask=0777
public=no
force user = pi
valid user = pi

I then told Samba to update (reboot would no doubt have done the same thing)

sudo service smbd restart

And that was it for the disk… on my PC at \\neo\share I was asked for username and password – I put in pi and my new password – this then became available on the network and I used Windows to MAP the drive – now drive Z: is that folder. A quick attempt to copy a 3GB file over proved successful.

The Real Time Clock:

So the NEO2 has I2c but like most non-Pi machines I’ve never been able to make use of that until now. The NAS box has a connector for this – nothing special but they’ve put the necessary pull-up resistors on so we don’t need to.

In a previous article I pointed out that FriendlyArm recently released a WiringNP at my request (and no doubt the request of others) and that is part of the operating system assuming you have their latest ROM. Well… I could not resist it.   I tried this:

sudo gpio i2cd

That’s the I2c scanner and hey – it worked – it spotted the real time clock on the NAS board. Could this possibly work? Well yes but the clock was wrong and the timezone was wrong so…

sudo timedatectl set-timezone Europe/Madrid
sudo hwclock –w
sudo hwclock –r

Sorted. Now I was getting somewhere – got serial, got access to some ports by the GPIO utility, got real time clock, I2c…

More I2c – the SSD1306 Display

It occurred to me that a little status display would go down well on that back panel.

I spent a lot of time trying to get other people's libraries to work with one of those SD1306 128*64 OLED modules with only limited success – of course the connector wiring was different. On the FA board it was gnd, 5v, SDA, SDL – which strangely is what Itead use – and the 128*64 OLED clock had clock and data the other way around. No matter as I had to solder to the OLED anyway. I plugged the board int (first checking the OLED could handle 5v) and sure enough – a quick scan revealed that address 3C was now used and I happen to know that’s the right address for the OLED (see my earlier blog on power supplies where I put one of these to good use.

I found one library that worked and talked about it in the previous version of this blog – yes it worked but it also killed the board by introducing a “segmentation error” which I simply could not get rid of.  I wasted a lot of time on the wrong libraries and eventually got in touch with FriendlyArm to see if they had anything - well, of course, they did! I should have asked in the first place.

They pointed me to something called Bakebit and in particular, code for the SEEED displays - which just happen to be the same as the generic 128*64 displays I use. I ended up on this page where I could do the install of the Bakebit code and examples.

Having done the install I very quickly realised that the Python PSUTIL library was version 0.5.0  - i.e. ancient. Using PIP I uninstalled that and put in the latest and though I was not not happy with the wide font they used. Again FrienlyArm helped out by pointing out that one of their examples uses TTF fonts – YES. Of course the example assumed you were running the Python code in the same directory that their examples and fonts were in – that took some figuring out – and there was a missing include.

sudo pip install Pillow

That sorted THAT out (don’t try missing the sudo off unless you are user ROOT – it appears to work then the board dies).

Here is my  displaying some stats.   As I'm planning to use a similar display with only two lines, I've since split the code to show 2 lines at a time, cycling continuously - but the info is the same. I managed to put a fully qualified link in the /etc/rc.conf folder – to have this run from power up.

OLED

</p>
<pre>
<code>#!/usr/bin/env python
#
# BakeBit example for the basic functions of BakeBit 128x64 OLED
#
# The BakeBit connects the NanoPi NEO and BakeBit sensors.
# You can learn more about BakeBit here:  http://wiki.friendlyarm.com/BakeBit
#
# Have a question about this example?  Ask on the forums here:  http://www.friendlyarm.com/Forum/
#
'''
## License

The MIT License (MIT)

BakeBit: an open source platform for connecting BakeBit Sensors to the NanoPi NEO.
Copyright (C) 2016 FriendlyARM

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''

import time
import bakebit
import os
import psutil
from math import log
import multiprocessing
import platform
import socket
import bakebit_128_64_oled as oled
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import socket
import fcntl
import struct
import sys
from datetime import datetime

global width
width=128
global height
height=64

global image
image = Image.new('1', (width, height))
global draw
draw = ImageDraw.Draw(image)
global font10 
font10 = ImageFont.truetype('/home/pi/BakeBit/Software/Python/DejaVuSansMono.ttf', 10);

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

oled.init()                  #initialze SEEED OLED display
oled.clearDisplay()          #clear the screen and set start position to top left corner
oled.setNormalDisplay()      #Set display to normal mode (i.e non-inverse mode)</code>
oled.setHorizontalMode()

<code>#oled.setPageMode()           #Set addressing mode to Page Mode




byteunits = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')
def filesizeformat(value):
    exponent = int(log(value, 1024))
    return "%.1f %s" % (float(value) / pow(1024, exponent), byteunits[exponent])

def bytes2human(n):
    """
    >>> bytes2human(10000)
    '9K'
    >>> bytes2human(100001221)
    '95M'
    """
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = int(float(n) / prefix[s])
            return '%s%s' % (value, s)
    return "%sB" % n
 
def cpu_usage():
    # load average, uptime
    av1, av2, av3 = os.getloadavg()
    tempC = ((int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1000))
    return "LOAD: %.1f %.1f %.1f" \
        % (av1, av2, av3)

def cpu_temperature():
    # load average, uptime
    av1, av2, av3 = os.getloadavg()
    tempC = ((int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1000))
    return "CPU TEMP: %sc" \
        % (str(tempC))

def mem_usage():
    usage = psutil.virtual_memory()
    return "MEM FREE: %s/%s" \
        % (bytes2human(usage.available), bytes2human(usage.total))
 
def disk_usage(dir):
    usage = psutil.disk_usage(dir)
    return "DISK FREE: %s/%s" \
        % (bytes2human(usage.total-usage.used), bytes2human(usage.total))
 
def network(iface):
    stat = psutil.net_io_counters(pernic=True)[iface]
    return "NET: %s: Tx%s, Rx%s" % \
           (iface, bytes2human(stat.bytes_sent), bytes2human(stat.bytes_recv))
 
def lan_ip():
    f = os.popen('ifconfig eth0 | grep "inet\ addr" | cut -c 21-33')
    ip = str(f.read())
    # strip out trailing chars for cleaner output
    return "IP: %s" % ip.rstrip('\r\n').rstrip(' ')
 
def stats():
    global looper
    draw.rectangle((0,0,width,height), outline=0, fill=0)
    if looper==0:
        draw.text((0, 0), 'WELCOME TO NEO2', font=font10, fill=255)
        draw.text((0, 13), 'Starting up...', font=font10, fill=255)
        looper=1
    elif looper==1:
        draw.text((0, 0), cpu_usage(),  font=font10, fill=255)
        draw.text((0, 13), cpu_temperature(),  font=font10, fill=255)
        looper=2
    elif looper==2:
        draw.text((0, 0), mem_usage(),  font=font10, fill=255)
        draw.text((0, 13), disk_usage('/'),  font=font10, fill=255)
        looper=3        
    elif looper==3:
        draw.text((0, 0),"%s %s" % (platform.system(),platform.release()), font=font10, fill=255)
        draw.text((0, 13), lan_ip(),  font=font10, fill=255)
        looper=4
    else:
        uptime = datetime.now() - datetime.fromtimestamp(psutil.boot_time())
        draw.text((0, 0),str(datetime.now().strftime('%a %b %d %H:%M:%S')), font=font10, fill=255)
        draw.text((0, 13),"UPTIME: %s" % str(uptime).split('.')[0], font=font10, fill=255)
        looper=1
    oled.drawImage(image)
 
def main():
    global looper
    looper = 0
    while True:
        stats()
        if looper==0:
            time.sleep(10)
        else:
            time.sleep(5)
 
 
if __name__ == "__main__":
    try:
    	main()
    except KeyboardInterrupt:
    	pass

</code>
</pre>
<p>

Some GPIO

I’ve had a quick check of the schematic – I may be missing something but it appears the following GPIO remains unused… GPIO-A0, C0,C1,C2,G6,G7,G8,G9, A1 and C3 – amongst those, you have UART 1 tx and Rx – and the SPI wires… might take some subtle soldering of the NEO2 but it is do-able to get these out.

Meanwhile Antonio wanted me to test the new disk I'd fitted:

sudo apt-get install smartmontools --no-install-recommends
sudo smartctl -H /dev/sda -d sat | grep overall-health | tr -d " " | cut -d: -f2

The disk said "PASSED" - and so off I went to order some connectors.

Replication:

This blog entry could just keep going on forever and I could turn it into a book... I decided to have a go at making a second unit.  Now, I could have started from scratch but there is a lot of work gone into this.  So - I made a new SD - just a basic operating system.  I put it into the second unit with a new drive and followed the steps I've already done right up to putting all the files onto the hard disk but I stopped before that.

It turns out you can use rsync remotely... so having mounted the hard drive and made a temporary folder - I repeated the rsync operation on the FIRST machine - but as ROOT to ensure I had permissions - but pointing as a destination the SECOND machine and that particular folder..... the destination (again addressing a ROOT connection at the other end) being root@192.168.1.44:/home/pi/tmp

And LO AND BEHOLD after asking for the password of that user, not only did it start the copy but it finished it within minutes.

I changed the settings in the boot file just as before but on the second machine this time - and rebooted. Stunningly, everything worked. I changed the domain name of course and rebooted again but I now have two identical machines both of which are now on solar.

Two units

I did have some difficulty in installing BakeBit but in the process, FriendlyArm wrote to say they had the LCD working – and they put a ROM up with the updated Ubuntu AND the Bakebit software already in there.   I’m waiting for a response to confirm that this ROM will stay online and I’ll update the blog accordingly. Essentially – install the Rom, install my script (for Node-Red etc) – add in the bits to run off a hard drive and you’re done. More on that later.

Update 27/05/2017

I’m waiting for confirmation from FriendlyArm but they have an image with the OLED code and example already in there. I’m hoping they’ll leave it available. It needs PSUTIL uninstalling and re-installing (2 lines) as the version they use is old – but other than that it works a treat. I DID notice that in the install is python-SMBUS and in the process of finding out what that was, I stumbled on some Adafruit code to run one of those PCA9685-based 16-channel PWM boards – you may recall some time ago I wrote about these and made my ESP8266 code compatible with them. Well, I could not resist it so I wired up one of the cheap Chinese PCA9685 boards to a connector and plugged it in.

After installing the Python library (one liner) I tried the example which outputs 2 levels of PWM for a servo. As I didn’t seem have a servo handy I tried a LED – and it worked a treat.

PWM board

Then I remembered that amongst some SEEED stuff, I did indeed have a servo.

ServoNow, if you’re not familiar with these, I guess the simplest way to explain at least this type of servo is that it is the kind of thing you see on model aircraft.

You feed it power and ground – in this case 5v… and a pulse signal – the width of the signal determines the position, accurately. I took the connector off, put on 3 new connectors and fastened it to the PWM board. Immediately it started moving from one extreme position to the other – perfectly.  I can’t believe how easy this was – and that little board will handle 16 of them (not power-wise but signal-wise.

NOW I was on a roll – I rummaged around and found a TG9e servo – yellow control wire instead of white but otherwise it looked the same – would I be so lucky – yes, worked PERFECTLY. Pity they’re not a lot larger, I could put them in charge of a solar panel!

All good fun and no doubt much more to come. I was beginning to think the only way to easily access control boards like this was to get a “genuine” Pi or ESP8266/Arduino – but it seems that this view is now history. I can imagine there are lots more drivers where these came from.

The Adafruit code I mentioned above includes drivers for the BMP085 (sadly not the BME085), TCS34725 colour sensor, VCNL4000 proximity detector, MCP4725 DAC,  DHT and a whole lot of other chips. Worth looking at. I’m sending off for a couple of 4-channel ADCs so I can monitor various battery voltages while the NEO2 is idling.

Port Extension

One of the things I learned early on when dealing with the NEO2 is that it does not like LOADS on it’s outputs. When I very first mastered the IO I had a bright LED on one of the outputs – and for reasons I put down to code, sometimes the board would not reset properly – or rather it would not come out of reset properly. I quickly discovered  that if I removed the LED – all was well.

So i2c comes in as something of a relief when you consider the magically cheap PCF8754T port extenders at under £1 each.

I hooked one of these with the 3 switches all OFF to the board and did the I2cd check – port 0x20. That was a good start. The next thing – and the limit of my achievement so far was to read these. I’ve already done this with the ESP and they are REALLY easy to use – fire the address off – issue a read and BOB’s your uncle. Similarly the write.

Of course I had NO idea how to use the I2c and went looking at the BMP example in the Adafruit folder.

This is what I have – now I should say from the start… firstly I have no idea how to use the libraries and I have even less idea how to use Python. But this works – I can read the port.

So the first thing to remember is that these devices do not swap modes – they are effectively open-collector – that is to say you if you set the outputs to 1 – they can be used as inputs and shorted LOW… they float HIGH.  if you use them as outputs and want to put any load on them – you need to take your load (a LED for example) from +v to the output – which will pull it LOW.

This is just as well as I could not find an 8 bit WRITE instruction – but there’s an 8 bit READ instruction with a parameter for writing to the control register… so RATHER handily you can just read, passing parameter 255. The pins will read 255 back unless you’ve shorted one or more to GROUND.

As outputs – imagine you have 8 (led+resistor) with the negative going to the pins and the common positives going to VCC, read(255) will output nothing – read (254) will turn the first LED on etc.  Works a treat. The only thing I don’t like about the cheap extender boards – come on guys – some more ground and VCC connections would have been nice!!!

From sheer guesswork to this…

#!/usr/bin/python
from Adafruit_I2C import Adafruit_I2C

i2c = Adafruit_I2C(0x20)
port = i2c.readU8(254)
print port

It doesn’t get any easier than this - clearly here you are importing the Adafruit library.  I had to put the library in the same folder as my code as I have no idea how to make a shortcut to it – which is apparently how it is done elsewhere.

i2c is what I would call an object (could be any name)– no idea what you call it in Python… and so you call the I2c setup function with an address – i.e. the address of the board and you get your object(i2c)  back. i2c.readU8 is a function you pass a value to – and it returns an 8-bit number. Simple as that. Make the number you pass 255 for all inputs, anything you want as a LOW output you simply invert that bit….. 254, 253 etc.

port expander

I’m sure someone will tell me there is a write function and that’s fine as I’m still new to this (I’m a whizz at C). And, erm, well, it works – so there’s your port extender – you could have 8 of them with different addresses – that’s 64 bits and if you mess something up in hardware, there’s a chance your NEO2 will survive!! I will modify this as I get more clued up!

Facebooktwittergoogle_pluspinterestlinkedin

Pretty Colours

We live in a world of colour and most of us have colour monitors. Why then should we put up with boring terminals?

terminal

I could have sworn I blogged about this ages ago but I can’t find it. Anyway, this is a short one. I have a range of boards from Raspberry Pi through NEOs, Beaglebones and many others and at one time or another I end up using the terminal – usually using WinSCP. In some setups the prompt is already pretty coloured – in other cases it is depressingly boring.

Here’s a quick fix  - different setups may vary and how you wish to do this may vary.

So your terminal prompt in Debian and Ubuntu (maybe others for all I know) is controlled by a simple variable called PS1.

Try it… go to this link… http://bashrcgenerator.com/

colour prompt generator

The page is great fun – you can decide what you want in your prompt – and what colour you want for each bit.

So the string you see in the right (white) box above right.  If you just drop everything right of “export” into your terminal – your prompt will immediately change, but you’ll lose it on power up.

In my case I found that /etc/bash.bashrc has one of these and I just replaced it. Then for the users I want the colour to work – I went to /root or /home/pi and edited the .bashrc file – un-commenting the line that says “

force_color_prompt=yes

and commenting out everything after that to do with the prompt… here is (and this will vary) what I commented out. It comes just after that variable assignment.

#if [ -n "$force_color_prompt" ]; then
# if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
# We have color support; assume it's compliant with Ecma-48
# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
# a case would tend to support setf rather than setaf.)
#   color_prompt=yes
# else
#   color_prompt=
# fi
#fi
#if [ "$color_prompt" = yes ]; then
# PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
#else
# PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
#i
#unset color_prompt force_color_prompt
# If this is an xterm set the title to user@host:dir
#case "$TERM" in
#xterm*|rxvt*)
# PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
## ;;
#*)
# ;;
#esac

And that’s it. Simple, trivial you may say but if you like a colourful world…

Facebooktwittergoogle_pluspinterestlinkedin

NEO2 NAS Part One

NAS BOXThis started off as a simple bit of fun to see if the FriendlyArm NAS box was any good – I had no idea it would turn out to be so much fun..  read on…

My first NAS was the NetGear ReadyNAS duo – some of you may recall this – possibly with mixed feelings – it wasn’t the fastest tool in the box and mine was one of the earlier ones which had the peculiarly stupid “feature” of not turning on until you pressed a button -  how dumb is that?

Well, it didn’t take me long to stick a micro on that so that it would always be on, but ultimately it was slow and disappointing.  I then moved onto a Synology DiskStation and I can’t speak highly enough of that. It has been sitting there for years in a cupboard, through thick and thin without even a battery backup, with a pair of 1TB disks in it running Raid – and the whole thing “just works” – holding all my video media, backups etc and I can access the info from wherever I happen to be – not to mention running MQTT and OwnCloud on it (the latter isn’t very fast but that’s another conversation). Would I trust it with my life? Probably.

So I’ve had a fair experience of these systems. Well, this blog entry isn’t about expensive NAS systems. It’s about a cheap one… really cheap that is – and DIY.

How cheap? Well, about £12 depending on what you have handy. For this price you need a handy 2.5” hard drive, a FriendlyArm NEO or NEO2 and of course the 1-Bay NAS Kit for NanoPi.  Beware that the front panels for NEO and NEO2 are SLIGHTLY different – i.e. the Ethernet connection position varies slightly so these are not cross-compatible without a spot of filing which is why I’m showing you the stock photo!

Anyway… so I plugged my trusty 100GB 2.5” hard drive into the board (well, it was free and was sitting doing nothing), plugged the NEO2 into the board, downloaded the ROM and.. well, that was it really – turned on the power (you need a 12v power supply) and waited. Sure enough the unit appears on my network. I’m cutting a long story short because in the link above, their link to the software is an image – I have suggested that making it a clickable link might be more sensible. Meanwhile they’ve sent this link for all the NEO (not NEO2) Roms.

The comments about the NAS side of things are based on the above ROM but as a result of feedback, they've just sent me a newer link - you might want to use this later link I received on 25/05/2017 and if you do THAT you might want to skip to this blog entry  - part 2.

Once you find the address of the unit on your network, you simply plug that into your browser and you’re asked for country name, username (admin) and the default password which is “openmediavault” – you can of course change all of that. No honestly it really is that simple to get started – sadly as you’ll see, not so easy to get finished.

OpenMediaVault

I have to say it looks very pretty and comes ready with users pi and fa. Oh, on the underside of the board is a battery holder – I popped in a battery and so the unit keeps time thought it is also able to get the time from timer servers so I’m not sure what advantage you get from putting a battery in.

Clearly we are not looking at a redundant-supply RAID NAS here but a simple box to store stuff in by a variety of mechanisms which you can see under “services” in the image above.

If you check the link above, you have speed comparisons, the NEO is not so fast, the NEO2 is faster but still not as fast as a Raspberry Pi 3 would be - but not far off and then – it IS cheaper and smaller. So the NEO2 looks like a good idea (see same link above for more info).

So all very simple to put together – indeed it only takes minutes – but how easy is the software to use? I clicked on the Diagnostics dashboard and that showed a list of services running – with what looked like slide switches.

slides

I’m not sure how clever that was as you can’t do anything with them and repeated pressing does nothing but looks like it should. So, off I went to the services section to enable SMB/CIFS- mainly as it had a little “Windows” symbol and I figured this might be the quickest way to make the disk available to my PC. I named that and hit save, only to be told I could not share user home directories as “they are not enabled”. I went off to “users” and enabled home directories.

I tried to enable home directories but that required a “device” and no device showed.

It turned out that the hard disk had not been “mounted” by default – I found THAT physical disks (all very logical really) and told it to mount… and so enough my 100GB disk magically appeared. Back to users.. and shared folders. NOW I could make a shared folder. It turns out that all the stuff I’d originally had on that disk was still there!

I went back to Physical disks and one of the options was “wipe”. I was given the choice of secure or quick – I chose quick.

Not so quick

I figured this must be because I’d mounted the disk.I quickly unmounted the disk under file systems. Back to the physical disk – wipe – quick wipe – this time it worked – so all pretty logical if you have a logical mind – shame about the pathetic error message above.

When wiping the disk – this message came up.

Message

Now of course all of this tech nonsense is nothing to do with FriendlyArm, it is a property of OpenMediaVault – and I do appreciate that this is free software – but come on guys – messages like that – if I wanted to use FDISK I would not be sitting here with a high level storage solution (as it says in the heading).

I assumed that was not really necessary and went back to mounting the disk. This time the option was wiped out but under storage I noted I could CREATE a disk – ok, I’ll bite. I selected SDA – i.e. the big drive and accepted the default EXT4 and gave it a name –“fred”. I was warned this could take some time and proceeded. Another dialog box popped up to say it was creating partitions and formatting the disk. So far, so good. GREAT.

Then followed a protracted period of gobbledegook.

gobblegook

At the end of this…

Bad Gateway

I tried mounting the disk and that worked but it said that out of my 100GB, 60GB was used. I went back and tried again.

THIS TIME the process completed perfectly but when I mounted the disk (which the process had noted was a 111GB disk) it still said that 60GB was used.

I decided to share the root folder in the hope I could see where that 60GB was going.

Now I could add a SBM/CIFS share. In users, I told the system to allow user pi to use the same password as admin.

In windows I noted NAS appear in my network – HURRAY – and it asked for a username and password. I put those in and was presented with NAS – an empty space.

I was kind of expecting to see a shared folder FRED. I checked back at the NAS and sure enough FRED did exist. BACK to the SMB settings I noted a SHARES tab. Nothing in it so I hit + and sure enough I could add FRED. I saved that and went back to my PC.

Sure enough – FRED appeared. Success?

I right clicked FRED and selected “MAP DRIVE” on my PC. Sure enough, now “FRED” appeared as a drive on my PC.

Right click properties revealed it as a 117 GB drive with 79GB used. Inside that I found home directories for FA and PI and a lost and found – but no sign of that missing  disk space. I tried to make a new folder in the root – it would not let me – fair enough. I went to the PI directory. I tried to make a new folder – it would not let me – NOT fair enough.

Back to the OpenMediaVault interface – I could not see anything that was STOPPING me making use of this drive as user PI but I went to shared folders and noted that user pa had permission to do absolutely SQUAT. I added read and write permissions. Back to my drive on the PC.  No difference – user Pi could not do anything.

It then occurred to me that I might have done the map drive bit with my default credentials – I changed that to user PI.

Nope – STILL no ability to create a new folder. The system said this user had read/write ability – the computer said NO. User PI can read/write, group PI can read/write, shared folder can read/write – but computer says no.

I even tried going back to the file system tab in OpenMediaVault and applying a quota to user PI. That produced this subtle message.

Eror message

So in summary…  if you’ve never used as NAS storage system before, this could provide you with hours and hours of fun where you can pretend to be a sysop.  If you have done this before – well, I’d start saving for a DiskStation which a trained monkey could use – life is too short.

As I was finishing the blog, and as if to  show me, ultimately, who was boss – this message appeared. I guess I’ve been told.

I'll show you - it said

At this point you might think the NAS software is not very good - but please bear in mind two things - this was a first release - and I've updated this entry to point you to a NEW release - also people have written in to say that actually it can be quite good - so maybe I just got in a little bit too early.

But trust me - not all was lost - not by ANY MEANS - head on offer to part two of this entry where I get a LOT out of the box and the NEO2.

Facebooktwittergoogle_pluspinterestlinkedin

NanoPi K2

What, not ANOTHER board from FriendlyArm? And yes, you’d be right to wonder why I’m doing a bunch of articles on them right now – well, it just so happens I got a box of stuff all at once so I thought I’d get them all out of the way at once.

K2[7]

So – why another board? If you’ve read my various blogs you will know that regardless of what operating system these SBC board from various places are supposed to come with,  I usually end up putting these boards onto Debian or more decently command-line Ubuntu and running my script on them.

The only exception were a couple of earlier boards from these guys which ended up as media centres – Kodi etc.  The T3 boards.  Well, they’re good but compared to a good phone, most of these Android installations are either low resolution, slow speed or both.  Indeed on a daily basis I end up apologising to the wife as the Android crawls along. I like to blame old versions of Android but ultimately most of these SBC boards are not as fast as a good phone. I often say in conversation – if only they’d use the chips used in phones…

And so it was that I opened up the K2 board from FriendlyArm and the big claim is 4K video. I had to give it a go, didn’t I, so I downloaded the Android setup from their site.

Now this board has a number of special features.  Firstly it has an infra-red input and they supply an infra-red handset – so no messing around – it just “works”.  Another feature which I don’t think any of the other boards manage – this board is size-compatible with the Raspberry Pi 2 and 3 – and that means – yes, you can use any of the millions of Raspberry Pi cases out there – and there are some beauties!!!  Nice.

Even then I wasn’t that optimistic about Android – after all I already have a media centre running and it takes some setting up – did I really want to go through all that again?

Ok, well I’ll cut a long story short.. YES, ABSOLUTELY. This is lovely. So the board has 2GB RAM which is more than any Raspberry Pi has ever had or apparently ever will. It has a standard microSD and I JUST happen to have a 64GB microSD which will give BAGS of room for movies.

And so I guess you’d expect me to rant on for ages about various features? Well, I’m not. It works and works extremely well. I’ve tried YouTube and Chrome searching for high quality movies and everything I throw at the board runs flat out – maximum settings I can see on Youtube are 1080p and the quality is excellent – my monitor isn’t high enough res for true 4K but watching the smooth videos I have no doubt the claim pans out. The remote works a treat. The only thing that is missing is a 3.5mm jack which would have been good as my HD computer monitor doesn’t have a loudspeaker attached!!

I say it is fast – it is but if you REALLY want to go to town there’s an eMMC connector on the board… personally I’m happy with the SD.

You can look up the specs online on the link above, but in short, an Amlogic S905 with a Mali graphics processor, 2GB RAM, Gigabit Ethernet, WIFI, BLUETOOTH, audio via HDMI or Bluetooth,  Oh, my headphones – hang on… testing…RIGHT – that sorts the audio – the Bluetooth works a treat with my little GEAR4 speakers – no problem.

I’m running this with the heatsink attached – which also has a fan but a fan is always a daft idea in a media centre… and… yes, I think you can likely get away without needing the fan… the fins are cool enough to touch continuously.  Right – I’m off to find a nice box for this.

Oh and it has a proper power connector but I just plugged in the microUSB connector and that’s working a treat.

 

 

 

```

Facebooktwittergoogle_pluspinterestlinkedin

NEO REBOOT

I have covered the FriendlyArm NEO and NEO2 boards here before now and generally been in favour – but for one little item in common with many other boards – little or no IO support – well, that just changed. Read on…

With no apparent way to get to the IO on this cute little board, I promised I would write to FriendlyArm and ask for WIRINGPI and that I did. In the meanwhile if you take a look at the relevant blog entry you’ll see I made a start at using GPIO the hard way and even found a WIRINGOP (OP – Orange Pi) variation that would do basic IO if you could guess the right IO pins, but that was about it.NEo2

Days later I received an email from FriendlyArm asking me to test their new WIRINGNP (as they call it) for both the NEO and NEO2.  I rushed to do the updates they suggested for existing setups but I hit a couple of snags (and reported my problem) – but they’ve also brought out a new ROM with the updates incorporated so I tried that on the H5-based NEO2. They have a WIKI on the subject. There are C examples for setting up soft PWM etc etc   - but here I  mainly use the GPIO utility that runs as user Pi and hence can easily be called from Node-Red or indeed – the command line.

The Ubuntu command line is pretty much what you might expect on any similar “Pi” and certainly it runs my script so I had no trouble testing the new WIRINGNP as they call it.  I was particularly interested in the GPIO program which a non-root user can run from the command line.

NEO2[1]Using their npi-config menu-driven command line tool I told the NEO2 I want to use PWM – you can also set audio, the welcome message, serial, I2c, SPI and PWM enable/disable. At that point the board rebooted with the new settings.

Now-  I’m terribly excited, the serial setup allows for enabling and disabling serial ports 0-3 (yes, FOUR serial ports) with serial port 1 enabled – we’d discussed this by email and this is what I was expecting – I didn’t expect a nice, easy menu setup for this – well done if it works…

After some diversion as they originally chose to refer to physical pins as against wPi or BCM pin designations -  I eventually realised that pin 38 (on a separate 4 pin connector) is the hardware PWM pin

gpio mode 1 pwm
gpio pwm-bal
gpio pwmr 1024
gpio mode 38 pwm
gpio pwm 38 100

The first four lines are setup and I discovered that line 1 was necessary despite being of no relevance to this board (1 on the Raspberry Pi is the PWM pin) – the setup for pin 38 follows as the second last line before setting the PWM value to 100  (out of 0-1024). A handy LED on pin 38 confirmed that the hardware PWM on that pin works.  I've asked FriendlyArm to check. Also if the LED load on this pin is too heavy,  reboot does not work but that I think is more down to the H5 processor.

Note also there is some kind of screen debug output when you run these commands and the C example – again I’ve reported that back to FriendlyArm as you don’t get this on the Rasperry Pi.

You can’t do any other kind of PWM on the other pins using GPIO – but that also applies to the Raspberry Pi.

For simple GPIO – let’s say pin 12

gpio mode 12 out
gpio write 12 1

Works a treat.

FriendlyArm also have conveniently made a user PI – so you don’t even have to create that though they persist on their site in assuming quite often that you are user ROOT – I have suggested they think about that as people are usually encouraged NOT to run as root. Running my script is as simple as dropping it into the PI directory – giving it execute permissions and running it. I ran my script to install Node-Red etc., so I could check out the serial ports.  Serial port 0 is normally used for debug and FriendlyArm suggested making serial port 1 available by default.

NEO SERIAL

As you can see in the image of my Node-Red setup for the serial ports (standard serial node) – I hooked up all 4 serial ports and in the case of serial port 1 – I shorted the input and output pins together. As you would expect – injecting into the ports brought back failures in 3 of them as they’re disabled – but in the second case – the timestamp was sent back. Perfect. I’m out of time but quietly confident the rest would work if I needed them. So in just this one respect – compare this to the Raspberry Pi 3 – it has Bluetooth and that conflicts with the serial port – you don’t actually have a spare serial port – here you have three.

At the end of this – the little NEO2 is going to end up talking to an Arduino Mega running that 433Mhz RFLink board as well as lots of other tasks.

I have yet to test SPI but as it stands – these boards are in very select company in getting support from their own manufacturer! Also - see the blog entry on the NAS - which ends up being about the NEO2 - thanks to the open source Bakebit I now have OLED displays running on these boards.

The following day I received an update: We’d discussed the various naming systems for pins – physical – ie. the actual pin number, wPI (Wiring Pi) and the BCM numbering schemes.  I suggested physical was probably best – but when the update came they’d implemented both for those for programming in C.

//using wiringPi Pin Number
int pin = 18;
wiringPiSetup ();             

  //using Physical Pin Number
int pin = 38;
wiringPiSetupPhys();                                          

  //using BCM Pin Number
int pin = 5;
wiringPiSetupGpio();

Well, I thought that was quite satisfactory!  Here’s a little test I tried – on physical pin 38…

test

such a program needs to be compiled as such:

gcc -Wall -o flashtest flashtest.c -lwiringPi -lpthread

The end program needs to be run as root  - WHY!!!!!!!

Anyway, sudo ./flashtest works – and I tested in the Node-Red EXEC function – it works in there (again using sudo  - no big deal). So it should be possible to make little C programs to do just about anything you want with GPIO and 3d Printed Box for NEO2call them from the EXEC node – which conveniently tells you when they’ve finished running – WITHOUT holding up the show!

More later – I’m hoping they’ll get rid of some debug stuff in there but this according to the WIKI can be setup for both the NEO (cheap) and the NEO2 (more powerful).

MEANWHILE a parcel turned up this morning – up to now I’ve not used the heatsinks on the NEO2 – ok it gets quite warm but not stinking hot – however – as the heatsink and board conveniently fit into the cute 3d printed box… I’ve now fitted it…  all looking very spiffy. Ok, 3d printed cases are not perfect- but for this – good enough!

Facebooktwittergoogle_pluspinterestlinkedin

Big Nextion

ITEAD DisplayQuite a while ago now I did a project based on the little Nextion displays, resistive touch-LCD displays which run on serial commands and come with an editor to make simply touch displays for even the simplest of micros.

Well, that project has proven to capture a lot of interest and I have one of those displays running 24-7 in a holiday rental property – and it has been doing that for a couple of years now.  I’ve not done anything new with the displays for a while but this morning, a new generation display turned up for me to take a look at.

The NX8048K070_011C is a new 7” Enhanced HMI Capacitive Touch Display complete with case (also available without the case) from Itead – the company who also produce the Sonoff units we’ve discussed many times in this blog.

The unit runs on 5v at 550ma and is to use the company’s own words, a powerful 7.0'' HMI TFT capacitive multi-touch display with a beautiful enclosure, with 32MB Flash data storage space, 1024 byte EEPROM, 8192 byte RAM, and GPIO supported.

The “GPIO supported” means there’s an 8-bit port connector. There is also an SD connector for storing info and a small 4-way connector for power, serial in and serial out.

So first things first – the advert headlines with $88 but in fact that is for the resistive version – for the capacitive version, add $20 for a total of $108 + shipping. The shipping via normal e-parcel was $11.40  (I’m only using dollars here because the ad is in dollars). DHL shipping is a horrifying $57 – but then I would not use DHL even if they threatened to cut off my toes. I STILL think the best thing ITEAD have done is the original Sonoff – and I say that because of the price. Right now they are going at $4.85, which for a boxed unit controlling the mains via WIFI is just stunning. The later units are in better boxes and are more powerful but by the time you reach $20 each the price to control a lamp is starting to get a little less enticing.

Anyway, I digress. So the Nextion displays work in a strange way – you don’t write directly to them like a typical Raspberry Pi display – but then you don’t have that overhead either. Once set up – which you do with the free “Nextion Editor” – the display merely needs serial text commands to do updates hence the simple 4-wire interface.

I’d rather hoped the rather nice display case would have some kind of feet – but instead it comes complete with 4 wingnuts which come complete with elongated bolts for mounting into existing installations.

One of the most annoying features of the original Nextions was the SD – you could not actually store data in it – that has now been addressed along with supplying real time clock, GPIO (well, on an ESP8266 you lose 2 wires to run the display so it can be useful to get that and more back) and of course the smoother capacitive touch display.

Display and caseThe actual display itself is only 800*480 which means you can see the dots but from any distance at all this is fine. The design of the case means it would easily fit into a cavity in a control panel and the whole thing is quite sturdy. I do wonder however why they made such a large case compared to the actual size of the LCD itself – as you can see in the photo.

As if to demonstrate the new features, when I powered up the Nextion display – it showed a swipe as you might find on modern smartphones – once I’d swiped, I was asked for a password (1111) – I put that in and the display proceeded to demonstrate the time and date. Might have made for a more posh demo if it hadn’t been set to 2044 – but never mind.

So, simple operation, nice easy, light touch compared to the older (but cheaper) resistive displays)  but at the end of the day, ease of use or otherwise comes down to the Nextion Editor – because they have done their own thing you really need to be able to use the editor to set the display up.

I downloaded the latest Nextion editor (free) on my Windows PC. After all this time it is still 0.47 – you might think considering the amount of time the Nextions have been out they would at least be to 1.0 – but then perhaps one should not judge a book by it’s cover.

Nextion Editor

It did occur to me that just MAYBE you could fit a little ESP8266 or NANO into that case – but on opening – no – not unless you cut off any connectors.   Oh, and I found out why the clock was wrong – there is indeed a battery connector on the board – but no battery was fitted – well, that accounts for that!

At this point, rather than going through all the fine detail of the , here’s a video.

 

Also take a look at my Nextion WIFI Touch Display -  the size is different but the general idea is the same. I’d like to hear from anyone who’s been using these displays for any length of time to hear what they think of the current editor – and what do you think of the price (please don’t write in to say you’ve used an old tablet  - already had that discussion). Is this good – or is there something better out there?

Facebooktwittergoogle_pluspinterestlinkedin

A Quick Plotly

Some time ago I wrote about HighCharts – a wonderful set of Javascript tools for doing graphs – and I gave an example of getting the graphs into Node-Red.  I’ll not repeat that as you have the link above.  At the time I’d not added in databases, I’ve since made some VERY simple code to bring in the charts from SQLITE -  I have to say it isn’t the fastest code in the world so I won’t embarrass myself by replicating it here. But at the time, my only limit was Node-Red Dashboard – there was as far as I could tell no way to get full screen or anything like it on a PC  -  until I took the plunge today and ask the right people – turns out that you can set an individual page in Node-Red Dashboard to WAY past the normal 6 blocks width simply by altering the size of a GROUP used only on that page.

Groups

So given block sizes set by default to 48px per block – by merely changing the maximum width in blocks you can easily get to full screen size for a given page – while leaving others alone. The result, using HighCharts (their JavaScript is free for personal use – you pay for commercial use)… below you see info I’ve been collecting in SQLITE3.

Graphs

In the above image you see multiple lines, with missing point filling, from 27th April until now – taken from a single SQLITE table where I have different topics for different lines and I store the value and date (and that’s about it) – I call the table “timeseries”.  So I pull out what I need, sorted into topics – and fill in the info required by HighCharts – the best way to pick this up is to read my blog item above and go have a play on their site.

And so it was that I got the full screen I wanted and one of the guys in SLACK said “have you tried PLOTLY?”  Well, I went off to their site and this was all commercial and you could pay so much a month – didn’t much impress so I went back into the conversation only to be told I was looking in the wrong place, had I noticed their OPEN SOURCE JAVASCRIPT?

I hadn’t of course but here’s the link.  Free for you and I  to use.  Better – it is also easy to experiment with it online as they use CODEPEN for demos.  So click on that CodePen link and you’ll see some code you can mess with and this result…

Plotly

You will see JS code you can mess with to change values – one of the things I like is smoothed lines.  So where you see “mode: ‘lines+markers’, add after that…

line: {shape: 'spline'},

and VOILA…

rounded

Note that the blue line is now nice and rounded… and it was that simple – I spotted that line in another example. Try altering the data. So if you put this and a link to the library (see the HighCharts example) you should be able to add this to a Node-Red Dashboard template – and from there it is a simple matter to add dynamic data.

Another line you can add in there is essential for me – as someone who occasionally loses data due to power outages or whatever…

connectgaps: true,

That does what you think it does! Here’s another way to play with Plotly - https://plot.ly/create/

I’m quite happy with Grafana… but you never know – this time next week they may turn commercial (or not) and Plotly looks like another contender for ultra-nice graphing with relative ease (I didn’t say just “ease” because for some folks none of this is easy – but it is do-able).

In practice:  I took this example from Codepen -  and inserted it into a template – well, it didn’t work did it. Turns out there were two things wrong – the default DIV – even with an ID attached – would not work – and I’m not 100% sure why but the remote CDN would not work either.

SO – I simply grabbed the minified .JS file from the CDN (put the address in a browser, save the result in a file) – transferred the .JS file to my /myjs/ directory on my Raspberry Pi (read the HighCharts and other blog entries in here for the reason I do that) and made a new simple div – voila – it worked.

Plotly in Node-Red

Here is the relevant code to put into the template..

<script src="/myjs/plotly-latest.min.js"></script>
   
<div id="plots" style="min-width: 100%; height: 100%; margin: 0 auto"></div>

Follow that with the script and make sure that the call at the bottom refers to “plots” – or whatever you call your div. I tried fixed pixel values in the div as well as 100% – all work as expected. Better still – when I viewed the page on my phone (Android 6) it worked extremely well.

Of course that is simple, static data but of course that isn’t the same as injecting data into the graph from, say a database. Also the time/date X axis right now is actually a string – so lines with different dates end up all over the place.

I fixed that in this little test – here is the content of the TEMPLATE

<script src="/myjs/plotly-latest.min.js"></script>
<div id="plots" style="min-width: 800px; height: 400px; margin: 0 auto"></div>
<script>
   (function(scope){
        scope.$watch('msg', function(msg) {
            Plotly.newPlot('plots', msg.data, layout);
        });
    })(scope);

var layout = {
  xaxis: {
    type: 'date',
    title: 'Time'
  },
  yaxis: {
    title: 'Value'
  },
  title: 'Connect the Gaps Between Data',
  showlegend: true
};
</script>
       

And a function to feed this with values – something that could be expanded to multiple lines and any number of values?

var dd=[];
dd[0] = {
  name: "The first trace",
  x: ['2012-01-01', '2012-02-01','2012-03-01','2012-04-01'],
  y: [55,33,11,1],
  mode: 'lines+markers',
  line: {shape: 'spline'},
  connectgaps: true
};

dd[1] = {
  name: "The OTHER trace",
  x: ['2012-01-03', '2012-02-01','2012-03-01','2012-04-01'],
  y: [22,43,66,77],
  mode: 'lines',
  line: {shape: 'spline'},
  connectgaps: true
};

msg.data = [];

msg.data[0]=dd[0];
msg.data[1]=dd[1];

return msg;

So there it is – Plotly – taking in arbitrary values from an arbitrary source and displaying on demand – the next step from this would be to change that function node to pull in stuff from a database.  For now I’ll leave that to the reader.

Have fun.

Facebooktwittergoogle_pluspinterestlinkedin

ESP8266 Code Update

The code that forms a series of articles on this blog has now not been updated for some time – simply because it “just works” and has been doing so reliably for many months. However, I’ve been wanting to add bits to it and my problem was I was running dangerously low on iRAM. This would not affect the stack or reliability but would just stop me from continuously adding code.

Well, thanks to Espressif that is now history. The latest Esp8266 SDK, released just days ago, fixes a number of things on the ESP8266 – you can find the SDK here – you will need it if you wish to compile code but of course ROMS are available as usual.  The upshot for me is the return of nearly 800 bytes of iRAM which is something of a breath of fresh air.

The software has been updated to version 1.8.5, the code is available here…  and the SDK here.

And if you’re wondering what on EARTH I’m talking about… if you’ve seen “the script” – this is what it was put together for in the first place.

Blowing the home control 2016 code

Home control 2016

Extract from the manual (which is the best source of info).

Home Control

Facebooktwittergoogle_pluspinterestlinkedin

Uninterruptible Supplies

Need a power supply with battery backup that shuts off your PI or similar gracefully when the battery gets low and starts up when the battery  recovers? I’m sure most of us who play with the likes of Raspberry Pis and other SBC boards as well as other devices, have looked at uninterruptible supplies at one point or another – I often use the little battery powered chargers you get for phones – and until recently I thought that was a universal solution – having powered my Pi in Spain for many months now on one of these and we get awful power cuts there – no problem.

08 May 2017: This is an update to the original article as I found a problem and came up with a solution!

Lithium chargingThen someone pointed out to me that SOME of these units turn off the output when charging. Well of course they don’t ADVERTISE that – so that’s a problem if you’re looking for cheap options.

So today I received from BANGGOOD a cheap circuit board that promises to do the job. As it happened my one and only Lithium in a torch left in storage over the winter had kicked the bucket… but I remembered I had a spare but dead battery pack for one of my laptops – and proceeded to open it up. Sure enough half a dozen Lithiums in there.

I took one out that looked clean – dead. Put it on my big power supply for a couple of minutes at 2 amps – it looks ok.  So now I’ve attached it to this little board and plugged the board into a decent USB supply. one of the little chips is getting a little hot as it pumps power into the board but I think it will be fine (update once the battery ha some charge this cooled off – then running a FriendlyArm SBC nothing at all got warm).   So after it had been on for a while to give the battery a chance to get some power, I plugged an SBC into it’s output. You can see all of this in the picture above. Worked a treat and the little board settled into a blue-flashing-light mode after a few seconds.   I repeatedly disconnected the incoming power – no difference, the SBC just kept going.

So if you want something new to play with…. and you’re aware of the dangers of going within 100 miles of Lithium batteries – you might want to give this a shot. At £2.37 inc shipping – you can’t really go wrong provided you give it a damn good test before doing anything serious with it.  I think I may make a little bank of them with the remaining Lithium batteries from my power pack.

http://www.banggood.com/37V-Liion-Battery-Mini-USB-To-USB-A-Power-Apply-Module-p-928948.html

I’ve had a look to see if I could identify the bits – the battery charging chip is easy and monitoring (2 of them) but can I hell figure out what is used to provide the 5v out boost.

But there is a catch! I only just discovered this...  If the battery is TOTALLY DEAD and you start things up - nothing happens - the battery doesn't charge - the load does not come on. Disconnect the load for a short time and the battery immediately starts to charge and you can now reconnect the load.

This got me to thinking about a solution and in keeping with the ultra-low costs above, here is my ultra-low cost solution..

An Arduino Nano with relay (total cost around £3 from AliExpress) can control the output of the unit via the relay. The analog input (A0) can attach to the battery while the NANO is driven by the output of the unit.  The ultra-low current consumption of the NANO when the relay is off should prevent issues....  so what is needed is this - when the power gets low, this unit should alert the Pi to shut down..  it does this with a GPIO bit (D11 in this case) and optionally via serial - a nice way to do this would be to output a JSON package.

Here is an example of testing the little board from power up..

{"voltage":0.62,"status":"init"}
{"voltage":5.00,"status":"init"}
{"voltage":5.00,"status":"starting"}
{"voltage":5.00,"status":"starting"}
{"voltage":5.00,"status":"starting"}
{"voltage":5.00,"status":"active"}
{"voltage":5.00,"status":"active"}
{"voltage":0.96,"status":"warning"}
{"voltage":1.08,"status":"warning"}
{"voltage":0.94,"status":"standby"}
{"voltage":0.97,"status":"standby"}
{"voltage":1.14,"status":"standby"}

So the output message is init - and stays that way - the power is seen to be adequate - and a timer starts - after X seconds the relay turns on. Next, the battery is seen to be low - a timer starts and a warning GPIO bit is turned on  - the Pi could depending on your software, choose to use either the serial signal or the digital input - and shuts itself down.  In my case, serial was out so a simple port input was used instead.

The output from the NANO then goes low and stays low until the battery voltage rises significantly. You HAVE to have "hysteresis" in there - i.e. a difference between ON trigger voltage and OFF trigger voltage as the battery is going to recover a little the instant you turn off the load.

Now then there is an important point here - the NANO in this case is running on 5v... and the Pi will be 3v3 - so in the case of the WARNING OUTPUT and the SERIAL OUTPUT if you use one, the other or both you will need LEVEL SHIFTING - the simplest being a pair of resistors - that is a resistor from the NANO output to the Pi and a resistor from that PI pin to ground - as you don't want 5v going into the Pi - the maths is simple - I'd make the first resistor say, 10k and the second (grounded) resistor, say 15k.  In my case I just used a simple serial 1K resistor to limit current.

OLED display on controller

What we have here is an AliExpress OLED display costing just a couple of pounds, a cheap supply as mentioned above – running on a single cell and running on an Arduino NANO.

For the OLED, the Adafruit library uses WAY too much RAM but this little number doesn’t.. https://github.com/greiman/SSD1306Ascii

Here’s a link to the little OLED display -  on a cheap Chinese Nano it uses pins A4 and A5 and you need to use a couple of pull-ups to 5v for the i2c. I used 2k2 as they were handy  - https://goo.gl/nXjpxd (another – possibly slightly cheaper https://goo.gl/PO0GiO)

Code here https://bitbucket.org/snippets/scargill/XLeLE

This unit also lets you set the max and min voltages and this is stored in EEPROM. I’m using 3.7 and 3.1 by default. Pins to ground for the controls are D5 for set, D6 for up and D7 for down.

And here’s a diagram kindly provided by Antonio, aka MrShark (on this blog comments) who’s been closely following this project! If you’re on a PC you can expand these images by clicking on them. Power supply is just the nearest available and does not represent the current supply you see in the photo above.

As for getting the Pi or whatever controller you are using to listen to port inputs – if you’ve a genuine Pi that should be no problem – I was using a NEO2 – not quite so simple until it all started to sink in – read this entry for more about accessing GPIO - http://tech.scargill.net/gpio-the-hard-way/

Board

Disclaimer: if this blows up your Pi – or worse – blows up – it is on your head! If you don’t understand the above – don’t do it. Make sure you have everything working and polarity is correct before attaching anything expensive.

Incidentally if you want to roll your own and find the above  text-only library for those OLED displays a bit limiting, the Adafruit lib is no good as it takes WAY too much RAM. The u8glib library on the other hand uses <400 bytes of RAM and has full graphics capability – here it is – I ran their standard test and it ran no problems – https://goo.gl/e2yVNM – if on the other hand you want speed, stick with the one I’ve used.

Facebooktwittergoogle_pluspinterestlinkedin

GPIO the Hard Way

I struggled with the title for this one as I figured if I put /sys/class/anything in the title – everyone would run away as I usually do.

This entry came about because of my utter annoyance that so many little Linux SBCs out there come with ZERO or very little support for GPIO.

Let’s take as a working example the NEO2 from FriendlyArm (and I’m not speaking out of turn – they know my views about not supporting this stuff).  Lovely little board – and today I was playing with my extremely un-elegant power supply backup solution (see previous blogs) and realised I had no idea how to access the ports.  It looks great in the advert:

  • GPIO1: 2.54mm pitch 24 pin-header, compatible with Raspberry Pi's GPIO pin1 - pin 24. It includes UART, SPI, I2C, IO etc
  • GPIO2: 2.54mm pitch 12 pin-header. It includes USB, IR receiver, I2S, IO etc

Lovely – grab your favourite Raspberry Pi utility – I like GPIO – the command line utility – or maybe the nodes in Node-Red – and your off and playing with GPIO.

I’m joking of course – none of that stuff works on these other boards though one or two have “equivalents”!  Sometimes the manufacturer provides utilities. I remember one provided some C code – lovely – then told me it only works for ROOT users… you know – the user you are not supposed to be !!! I can only get ONE of the four serial ports to actually work in Node-Red even thought it reports they are there (not permissions – tried that).

Anyway, recently I sat down with a large glass of artificial strawberry drink and started reading.

There is a directory in most of these boards in Linux called /sys/class/gpio

So I went looking – sure enough the NEO2 had this – and a couple of files and 2 shortcuts to GPIO that meant absolutely nothing to me.

So here’s what I’ve learned – just by messing about mind you.

You have to expose the GPIO – so let’s take GPIO0 as a working example.

As root user:

echo 0 > /sys/class/gpio/export

This made a GPIO0 magically appear.

echo out > /sys/class/gpio/gpio0/direction

This made the GPIO an output

echo 1 > /sys/class/gpio/gpio0/value

This made the output go high.

Sounds simple – but which I/O – I made 2 variations of that last command – one with 1, one with 0 – and played them back and forth while sticking a LED on the various potential IO pins on the NEO2. Voila – a lot simpler than I was expecting it turns out that GPIO0 was PA6 on the NEO2.

Now I was getting excited – but here’s the thing – I needed to control this output from Node-Red – and my Node-Red is user PI and you can’t DO this command as user Pi. You could use SUDO but SUDO doesn’t work with echo.

pi@neo2:~$ echo 1 >  /sys/class/gpio/gpio0/value
-bash: /sys/class/gpio/gpio0/value: Permission denied

Arggghh. But simple? Use Sudo

pi@neo2:~$ sudo echo 1 >  /sys/class/gpio/gpio0/value
-bash: /sys/class/gpio/gpio0/value: Permission denied

Aaarrrrrggghhh.

So I spoke to my friend Antonio and he came up with TEE.

echo 1 | sudo tee /sys/class/gpio/gpio0/value

Aaaaaah. WORKS – so now I put this into an EXEC node in Node-Red and tested – WORKS.

Exec node[10]

As you can imagine the next step would be to waste hours trying to find out which ports you can use – but then I realised that at least in this case  - FriendlyArm supply the Linux GPIO names! I tried GPIO2 – bingo! Nothing is permanent – so a little code in Node-Red would need to check if a port had been used before – and set it up as an output first if not – that’s easy – a lookup table for meaningful names and a bit of substitution in a function would also be easy.

Could I get this to work with inputs? SURE – almost the same starting with “in” instead of “out” assuming you’ve already exposed gpio0...

echo in | sudo tee /sys/class/gpio/gpio0/direction

The next part was sheer guesswork

cat /sys/class/gpio/gpio0/value

Sure enough – this returned the value of that port – either 1 or 0. Would it work in Node-Red EXEC?

exec node[6]

YUP! Works a treat. So you could write something for this outside of Node-Red but the latter is a nice friendly environment – and the use of a global would let you check if the input or output was already in use – this is readily adapted to other gpio-software-challenged boards.

This is course is trivial – it does not answer how to use peripheral features such as I2c etc. but if you’ve been struggling just to get the very basic input and output – perhaps that part of your struggle is now over.

Someday soon I hope to have proper drivers for the ports on this and other devices – but then someday soon I hope to win the pools. Best not wait around too long for either.

Meanwhile I have my input and now I can set about detecting low power – and shutting the device down gracefully – just need to write a little code to set up  that input automatically.

So – first things first – here’s a setup I’ve made for the NEO2 – a simple text file called “pins.def” (for want of a better name) in the /home/pi/.node-red directory (for want of a better place).

{ "0":"in","203":"in","6":"out","67":"out"}

A simple piece of json defining the ports I’m interested in – and their direction.

I discovered that if I sent the two commands separately there was no guarantee that they would get there in the right order – so I joined them together… for example for GPIO0

echo 0 | sudo tee /sys/class/gpio/export; echo in | sudo tee /sys/class/gpio/gpio0/direction

And here is my test rig in Node-Red

Tesrts

One of those ports – GPIO6 is an output and is a good test…(pin12 on the dual connector on the NEO2).

Simple enough – on power up the injector node fires off anything to the yellow function node which sets up the ports by exporting them and setting their direction.

var fs = global.get("fs");
var fl="/home/pi/.node-red/pins.def";

var pins=JSON.parse(fs.readFileSync(fl).toString());
for (var port in pins) {
if (pins.hasOwnProperty(port)) {
msg.payload=port + " | sudo tee /sys/class/gpio/export; ";
msg.payload+="echo " + pins[port] + "  | sudo tee /sys/class/gpio/gpio" + port + "/direction"; node.send(msg);
}
}                   

Insert your own error stuff as desired.

That’s it – the tests simply fire off the right info as described above to the EXEC node – I’ve tested this from reboot – it works.

Now – remember the point of this – I wanted to be able to check a port to see if I should gracefully power down the Pi if the port was low? Well, I can check that every 10 seconds like this.

tests

Of COURSE I can make this more graceful. So every 10 seconds – I trigger the cat command on GPIO0 – RBE merely outputs only on change – probably not needed.. then a simple function returns ONLY if the output is HIGH…. and shuts down the NEO2.

Easy – you could adapt this to any setup.

And here is a new project where this is in use - http://tech.scargill.net/uninterruptible-supplies/

Facebooktwittergoogle_pluspinterestlinkedin