Raspberry Pi & PHP & Swift

I may have mentioned in previous posts that I’m working on a PHP port of my MonoPi and jsRPi frameworks for the Raspberry.  The project is WELL underway and a great deal of progress has been made. The core and some of the extensions are already done and I’m now beginning work on the “Components” and “Devices” portions of the framework.  Also, I just read a really interesting article about getting Apple’s Swift compiler running on the Raspberry Pi 2 (will also work on the Pi 3).  I’ve been wanting to try out Swift for a while now but none of my Macs are new enough to run new enough versions of XCode to get the Swift toolchain.  However, Apple recently open-sourced Swift, and luckily plenty of people have already gotten to work porting it to other platforms such as Linux and now there is a working port for the ARM7 architecture under Linux.

This pleases me.

One of the things the article mentions is a need for libraries that allow access to Raspberry Pi hardware such as GPIOs….

Well… As you can imagine, this is a bit like the perfect storm for me.  I get to learn and code in Swift *and* port my framework to Swift at the same time. Boom. So now how am I going to go about this?  Well since I can’t really use my Mac for the dev work, I *can* use my PC running Linux and thankfully this fella built an Atom addon for Swift dev and debug that I can use for exactly that. I am so excited I can barely stand it.  Now I gotta hurry up and get this damn PHP port done so I can start on it.


UPDATE: Turns out you can do unit testing in Swift under Linux too.  Apparently, Apple also open-sourced XCTest.

CyrusBuiltHTPC v2.0 Released!

I’m happy to announce that the new version CyrusBuiltHTPC has just been released.  Version 2 is an extensive overhaul that fixes the ATX PMU firmware, upgrades from XBMC to Kodi and if you are still running Raspbian “Wheezy”, the setup scripts will upgrade you to Raspbian “Jessie” (Kodi v15.x works best on Jessie).  This build of Kodi fixes the “Black Screen” issue that would occur when exiting Kodi.

Interfacing with a Raspberry Pi using NodeJS

Well…. I’ve been gone waaaaayyyy too long.  I’ve been on an extended hiatus while my personal life self-destructed, then began to rebuild, then had a serious car accident, then ended up battling major health issues (chemo is a bitch), and then the road to recovery.  The good news is, my hands have been anything but idle.  During all that I pushed out another release of my MonoPi framework, a joystick library for the Arduino, another release of my CrystalFontz LCD library for Arduino, and finally: a NodeJS framework for the Raspberry Pi, which is essentially a port of my MonoPi framework to NodeJS.  I call it jsRPi.  Yes, there are a couple other Node modules that exist for interfacing with a GPIO, but with all due respect to their authors, I find them lacking for my purposes.  MonoPi and pi4j offer a wide breadth of functionality that the existing modules for Node simply don’t have.  All of the existing modules I found offered only the most basic read/write capability for the GPIOs.  jsRPi, on the other hand offers that plus various system utilities, hardware abstractions for relays, motors, LEDs, etc and device interfaces for PiFace, PiCamera, PiBrella, sprinkler control, etc.

The reasons I decided to take on such an ambitious project were:

  • I wanted to teach myself NodeJS (and become more proficient with JavaScript in the process).  Porting a large framework like MonoPi seemed like a good way to do this.
  • No other modules/libraries/frameworks as extensive as MonoPi exist for Node.
  • I ultimately intend to write a web app using NodeJS and Express and React.  Being able to write the entire thing in JavaScript would be a huge win.

Getting Started

Head over to my github repo and download the source or clone the repository, then from a command line, navigate to the jsRPi folder (as of this writing, the framework is still an Alpha so I have not published an npm module yet).  Then follow the instructions in the README to install dependencies and build the source.  I should note that the term “build” when in comes to jsRPi really just means check all the syntax, generate API documentation, run unit tests, and produce an optional version of the framework “compiled” into a single file.  Build tasks are executed using Grunt.  If you don’t already have Grunt and grunt-cli, it will be installed when you run the appropriate install_deps script.  You can also run just the unit tests by entering the following command from the command line (from within the jsRPi root directory):


grunt nodeunit


Blink Example

The following example shows how you can blink an LED.  This example assumes you have an LED and appropriate resistor connected to GPIO-00:


'use strict';
var jsrpi = require("jsrpi");
var GpioPins = jsrpi.IO.GpioPins;
var PinMode = jsrpi.IO.PinMode;
var PinState = jsrpi.IO.PinState;
var GpioStandard = jsrpi.IO.GpioStandard;
var LEDComponent = jsrpi.Components.Lights.LEDComponent;
// Setup the pin.
var ledPin = new GpioStandard(GpioPins.GPIO00, PinMode.OUT, PinState.Low);
// Create an LED and attach it to the pin.
var led = new LEDComponent(ledPin);
// Blink the LED once per second, for 5 seconds. This is an asynchronous operation.
led.blink(1000, 5000);
// Destroy the LED. Note: You do not need to call dispose() on the pin. It gets disposed by LEDComponent.
setTimeout(function() {
}, 6000);

Again, this framework is currently an Alpha release, so I expect there are probably bugs, particularly in the parts I have not yet been able to test for lack of required hardware. Future plans include, refactoring to be ES6-compliant, include callbacks as optional parameters for asynchronous methods (WHY ON EARTH I didn’t do this in the first place is beyond me. Hence, disposing the LED using setTimeout() shown above), and hopefully native RS-232 serial support (present in MonoPi, but not yet ported to jsRPi). I should also mention that I’ve already begun porting to PHP as well. So keep your eyes peeled for “PHPi”, coming soon!

All of this is part of an even larger project that I’ve been prototyping with quite a bit of success:

A home automation controller using an Arduino Mega 256 w/Ethernet Shield to control power outlets (which mostly just control lights), and a REX (Request to EXit sensor) , which is just a PIR (Proximity Infra-Red) sensor that triggers an onboard relay.  The Arduino has its own built-in web interface for configuring settings like the network interface (static IP or DHCP, etc), and ultimately communicates with a Command And Control server running on a Raspberry Pi with Mosquitto (an MQTT service), which I use to send commands to and get status from, the Arduino.  Then a small web app also runs on the Pi that communicates with Mosquitto to provide a GUI that can run from a phone, tablet, laptop, whatever and control the lights. It also has an “away” mode which makes use of the REX. When you leave, you put it in “away” mode and then walk out the front door.  When you come back through the door, the REX sees this and switches on the lights for you automatically and switches “away” mode back off.  Pretty slick.  All of the pieces of this project will eventually be detailed here and published to my github page as I complete them.  Stay tuned!


I love my Raspberry Pi.  I built an HTPC around one and I use it almost every day.  It suits this purpose quite well.

But, I don’t really take full advantage of the Pi in this capacity.  Afterall, there is most of a GPIO header on that thing that I’m not using for anything.  Recently, I was working a home automation project using an Arduino.  I kept running into roadblocks concerning capacity.  If (for example) you take an Arduino Uno R3, add an Ethernet Shield w/SD Card slot and then implement the all the libraries and essentially turn your Arduino into a mini-webserver, you’ll quickly find that you don’t have a whole lot of room for your program.  And if you want to implement a library to read/write INI files on your micro SD card, you have even less room.  Even with an Arduino Mega, you aren’t left with much space to do anything really cool or complex.

Most of the code I wrote, simply wouldn’t fit on the Arduino.  Even after countless optimizations, cutting out chunks that weren’t 100% necessary, removing some error checking code, etc., I usually still came up a little bit short.  The only option was to remove functionality, split it up into chunks across multiple Arduinos.  So naturally, when you look at this from a cost perspective, it just doesn’t make sense. Enter, the Raspberry Pi.

I mean, in terms of processing power and program capacity, it’s several orders of magnitudes greater…. for $35.  Granted, these are 2 totally different platforms, but that is my point:  I was trying to use the wrong tool for the job.  *Can* it be done with an Arduino-based platform?  Given the right additional components and some clever and highly-optimized code, yes.  Or, you could just install Apache on a Raspberry Pi, and actually be able to build *real* web pages and take advantage of CSS and JS, etc and not be constrained by space problems.

It’s still small, still low power, and still network and web-enabled.  Now, there is a bit of work necessary to turn a Raspberry Pi into a webserver.  Not much more than you would on any other Linux-based machine, but if you’ve never done it before, it might seem a bit tedious and confusing.  The standard deployment is know as LAMP (Linux, Apache, MySQL, and PHP).  To automate the deployment process to make things easier on myself (and I also figured it might make things easier on the newbies to get started), decided to build a tool to do all the hard work for me.

I call it LAMPi.  You can find it on my github page.  You just download it, unpack it, then run the ‘ilovelamp’ script (the play on words was intentional) and let it do the rest.  Optionally, it can also install VSFTP server and phpMyAdmin for you as well.

Go check it out.

CyrusBuiltHTPC Update

I’ve finally released a new build of CyrusBuiltHTPC for Raspian Linux.  This new build will install the latest XBMC (12.2 “Frodo”) and configure your Raspberry Pi as a full-fledged HTPC with the following features:

1) AirPlay support
2) TVHeadEnd support
3) libCEC support, so you can control it using your TV’s remote.
4) Support for relocating rootfs to an EXT4-formatted USB HDD.
5) A ~60% reduction in overall CPU usage.
6) Support for the DS1307 Real-Time Clock.
7) XBMC can now be updated just like any other package in the system via “apt-get update” or using the “systemupdate” tool installed with CyrusBuiltHTPC.
8) Reduced memory usage footprint to ~40MB on average.

NOTE:  This has only been tested with the Raspberry Pi Revision 2 Model B.  IT HAS NOT BEEN TESTED ON PREVIOUS RASPBERRY PIs AND LIKELY WILL NOT FUNCTION CORRECTLY.

This build makes use of the pre-compiled DEB packages built and maintained by Michael Gorven (cocooncrash).

Usage instructions:

Once you’ve pulled down the source package, navigate to the CyrusBuiltHTPC/CyrusBuiltHTPC folder in the terminal and then type “chmod +rx remote_install.sh”.  If you have not already done so, enable the SSH daemon on your Pi.  Then run “./remote_install.sh” in the terminal and follow the prompts.  This will push the CyrusBuiltHTPC package to the home folder of the Pi user (or whichever user you specified).

On the Pi, navigate to ~/CyrusBuiltHTPC in the terminal and type “chmod +rx setup.sh” and then run it “./setup.sh”.  This will make all the necessary scripts executable and install some system tools.  You can now run commands like “systemreboot” to reboot the Pi immediately or “systemshutdown” to gracefully power off, or “systemupdate” to upgrade and update the system.  You can also backup and restore the system configuration files modified by CyrusBuiltHTPC setup.  To proceed with installing XBMC do “cd ~/CyrusBuiltHTPC/xbmc_install” and then “./get_and_install_xbmc.sh” from the terminal.  This will add Michael Gorven’s APT repo for XBMC and then pull down XBMC and any necessary dependencies and install it all.

Once finished, you will be prompted to run the platform configuration utility.  This will install RTC support, some additional tools, configure XBMC to auto-start on boot, grant the authority to XBMC to shutdown and reboot the system, and give you the option to relocate rootfs.  This will also overclock the system to 800MHz and set the memory slice to 128MB/384MB.  As prompted, you will need to reboot the system for the configuration changes to take effect.  If you chose not to run the platform configuration utility, make sure you are not booted into desktop mode (pure console, not running X11/Xorg), and run “xbmc-rpi” to launch XBMC.  The xbmc-rpi script will store the current terminal settings before launching XBMC and then restore the terminal when XBMC quits so you are left with a black screen afterward.

I plan to make this available as a custom distribution of Raspbian in the form a disk image that you can just plop onto an SD card and go with.  But this will be a little ways down the road.  Hop on over to my GitHub page to get the latest CyrusBuiltHTPC stuff.



USB-to-SATA adapter and 250GB Hitachi HDD.  Relocated rootfs to the HDD to eliminate writes and reduce reads from the SD card. The SD card is only used for bootstrap, and then hands off to the HDD.
USB-to-SATA adapter and 250GB Hitachi HDD. Relocated rootfs to the HDD to eliminate writes and reduce reads from the SD card. The SD card is only used for bootstrap, and then hands off to the HDD.


Raspbian up and running on the HTPC.  Once I work out on the compilation issues with XBMC 12.1, I'll post pics of that too.
Raspbian up and running on the HTPC. Once I work out on the compilation issues with XBMC 12.1, I’ll post pics of that too.


And there you have it.  A fully-functional HTPC (connected via HDMI to a 1080P HDTV) that also works as a full-blown Linux desktop.  CEC is also working, so if the TV is off with the HTPC turns on, the TV will turn on and switch to that input.  Likewise, XBMC can be controlled using the TV remote because the TV essentially becomes a peripheral of the HTPC via libCEC.  Thanks to my PMU, it behaves much like a PC would in the sense of power on/off, reset, auto-off on shutdown, etc.  The only thing it does not do yet is power on via remote control (…. yet).


The Raspberry Pi (Model B., revision 2). The brown & black wires go to the RPi reset, and the colored cable goes to the RTC. The purple wire is for shutdown detection.
The Raspberry Pi (Model B., revision 2). The brown & black wires go to the RPi reset, and the colored cable goes to the RTC. The purple wire is for shutdown detection.


Better shot of the Pi with the 2-pin header added to the board for reset.
Better shot of the Pi with the 2-pin header added to the board for reset.
The DS1307-based Real-Time Clock (RTC) from Adafruit (http://learn.adafruit.com/adding-a-real-time-clock-to-raspberry-pi/overview)
The DS1307-based Real-Time Clock (RTC) from Adafruit (http://learn.adafruit.com/adding-a-real-time-clock-to-raspberry-pi/overview)


The DC-to-DC ATX power supply. The connector was removed and the wires fed into a terminal block for easier wiring. The PMU is powered off the +5V standby lead from PSU (purple lead) and the green wire is the ATX trigger.
The DC-to-DC ATX power supply. The connector was removed and the wires fed into a terminal block for easier wiring. The PMU is powered off the +5V standby lead from PSU (purple lead) and the green wire is the ATX trigger.
Wireless keyboard/mouse combo.  TV remote shown for size comparison.
Wireless keyboard/mouse combo. TV remote shown for size comparison.




I finally got around to taking some photos of my HTPC.

Here it is fully assembled in its Mini-ITX chassis
Here it is fully assembled in its Mini-ITX chassis


And here is the front bezel of the chassis (Power button w/LED, HDD LED, reset button - the big red one)
And here is the front bezel of the chassis (Power button w/LED, HDD LED, reset button – the big red one)
With the top off. Top tray holds the HDD.
With the top off. Top tray holds the HDD.


And here's all the guts. The middle board is the PMU I designed. It is controlled by the blue Arduino Micro on board.
And here’s all the guts. The middle board is the PMU I designed. It is controlled by the blue Arduino Micro on board.


Close-up of the PMU. The green terminal block on the right is power input. The block up top is the switched power (to RPi and HDD).
Close-up of the PMU. The green terminal block on the right is power input. The block up top is the switched power (to RPi and HDD).


Raspberry Pi ATX power management using an Arduino (Pt. 2)

Well, I finally posted all my source code and schematics on github at https://github.com/cyrusbuilt/CyrusBuiltHTPC.  Now some details on the Arduino code: To enable debug mode (if necessary…. it’s been thoroughly tested and I’m currently using it on my own box everyday), uncomment line 45 in Raspi_ATX_PMU.ino.  If you do, the firmware will not complete initialization until it connects to the host that will be monitoring the serial output.  It will attempt a serial connection at 9600 BAUD and will not do anything else until connected.  This is intentional so that you can see the boot screen which displays the pin definitions and their current state. Otherwise, you’d miss the boot screen by the time the connection is actually made.  Once connected, all actions and pin states are output to the serial port as the events are handled.  The 2 libraries in the “lib” folder will need to be copied to the “libraries” folder of your Arduino installation in order to compile.

And now some notes on the HTPC platform installation stuff:  Use the following procedure to set up the platform correctly: 1) Make sure SSH is enabled on the Raspberry Pi.  2) Navigate to the CyrusBuiltHTPC folder from a terminal and type “chmod +rx remote_install.sh”. This will make the remote installation script executable. 3) Type “./remote_install.sh”.  This will just push all the platform installation stuff to the Pi using SCP.  If you’ve already copied the platform installation stuff to the Pi by other means, then just skip steps 2 and 3. 4) Type “chmod +rx setup.sh” in the terminal on the Pi (or via SSH), and then type “./setup.sh”.  This will perform the initial setup by setting the appropriate permissions on the other scripts and installing the utility scripts (systemreboot, systemshutdown, systemupdate) in /usr/bin. 5) Navigate to /home/pi/xbmc_install in the terminal and type “./build-and-install-xbmc.sh”.  This will pull XBMC from its github repository and proceed to compile and install XBMC.  This may take up to 13 hours to complete. 6) After rebooting, navigate to “~/” and type “./configure-htpc-platform.sh”.  This will configure the platform appropriately and set up the Pi to boot into XBMC automatically (you can still exit XBMC to get to a command prompt).

The whole system performs well.  I’ve been streaming TV shows in HD from my TVersity server for months without any problem.  I think I can reduce boot time by relocating rootfs to the USB HDD, as described here.  I will post some pictures of the HTPC and some additional schematics laying out how the whole thing is supposed to be connected together.



Ok, so I’ve been playing with a couple of Arduinos for a while now.  I love these things…. soooo many possibilities.  I used to use the Parallax BASIC Stamp 2P24 for similar purposes, but quite frankly, they are just too expensive to compete with the Arduino (or Raspberry PI for that matter).  Plus, I don’t really care for the PBasic programming language either. The Arduino essentially uses C/C++ and the libraries are extensive.

Anyway, I bought 2 of these guys.  I started with an Arduino Uno and did some experiments and prototyping with it.  After playing around I had a cool idea….. remember when I said I got a Raspberry PI a while back?  Well, I had decided to build an HTPC using the PI, a Mini-ITX chassis w/power supply, an RTC (real-time clock), and some other goodies.  I found that Raspberry Pi + Raspbian + XBMC (Xbox Media Center) = One badass HTPC.  I mostly stream video from my TVersity server, but I also added a 250GB 2.5″ SATA HDD using a USB-to-SATA adapter.  The power supply that came with Mini-ITX chassis is more than ample considering the Pi only uses 5V @ 0.5A DC.  The bulk of the power consumption is spent on the HDD.  I also got a SWEET mini wireless keyboard/mouse combo so I can work the whole thing while sittin across the room in bed.  I can even surf the web!

1) There is a lot of work to getting XBMC compiled and installed on Raspbian.  There are pre-built images that have a stripped-down OS based on Raspbian with XBMC already integrated as a self-contained HTPC OS.  They were great, but did not support I2C or the DS1307 (both needed for the RTC module), nor did it have adequate support for my USB-to-SATA controller.  I found it best to just build XMBC on top of Raspbian and then customize the whole thing as needed.

2) Power.  The Mini-ITX chassis uses an ATX-style power supply.  It also has power and reset buttons, as well as power indicator LED in the front bezel just as you’d expect from any other PC.  The problem is this:  The Pi does not behave like an ATX-class PC.  You can soft-off through the OS, but it does not power off the board.  You have to disconnect and then reconnect the power in order to get it to boot up again.  However, there are 2 solder pads on the Pi used for reset.  So then I got the idea:  I could build a PMU (power management unit) using an Arduino!!

As it turns out, the ATX specification has a 5V standby pin (purple wire) that is always on as long as it has power.  This is what keeps certain functions of your motherboard alive so it can monitor power button presses, which then tells the power supply to turn on by driving the trigger pin (green wire) low, or in other words, ties it to ground.  So my thought was to use the Arduino to sense power and reset buttons and then drive relays to to control them.

But that is where I ran into problems.  I started off trying to use an ATtiny85 and just program it using my Arduino Uno as an ISP, but that didn’t work out because I couldn’t get the damn thing programmed.  I eventually gave up and bought an Arduino Micro from AdaFruit.  Not as cheap as the ATtiny85, but far more versatile and a breeze to program.  Plus it supported a greater instruction set, which I ended up needing anyway.

Then I ran into another problem:  Power draw.  The Arduino Micro, plus LED and a couple of relays is just too much power draw from the 5V standby pin.  I did not have sufficient power to run the whole circuit.  So, plan B: tie the trigger pin low leaving the ATX supply on full-time (or while it to a switch for hard-disconnect).  Then I can use the full 12V and 5V rails from the ATX supply.  The only thing is, I had to add a third relay.  The relay assignments are as follows:

Relay 1 = Reset switch.
Relay 2 = 5V power switch for Raspberry Pi and HDD.
Relay 3 = 12V power switch for HDD.

So the basic operation is simple:

Power button press (momentary):
Power currently on? no-> turn on LED and Relays 2 and 3. Otherwise, turn them all off.

Reset button press (momentary):
Power currently on? yes->turn off LED and turn on Relay 1. Do not switch states back until button release. During this time, ignore power button presses; Otherwise, do nothing.

This was actually quite effective.  The prototyping phase is done.  I just need to start soldering this stuff to the PCB!!  I’ll be posting schematics, source code, etc to github as soon as I get everything put together and tested.