C/C++

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.

Wednesday, December 2nd, 2015 Arduino, C/C++, Hardware, Programming, Raspberry Pi No Comments

Joystick Library for Arduino

In my previous post, I briefly mentioned that I had released a joystick library for Arduino.  I thought I oughtta expand on that a bit, especially since I use it quite a bit these days.  I’m the CTO of the family landscaping business.  One of the services we provide is snow removal.  As such, we have multiple snowplows.  All of the plows have hand-held controllers that control blade movement (raise, lower, pan left, pan right).  One of the controllers blew up, so we ordered a new one.  The new one blew up too.  So we got copies of the schematics and went over it with our mechanic looking for wiring faults that may be causing the failure.  We couldn’t find anything.  We then manually manipulated the plow by shorting wires in the wiring harness and in all our testing did not encounter any problems.  We had the last controller replaced under warranty.  After a couple of weeks, the replacement blew up too.  So I tore it apart and discovered that it was basically just a microcontroller that read button inputs and then triggered one or more solid-state relays to control the plow.  The problem was, I could not find any protection circuitry on the outputs.  So, when the magnetic fields collapse for the pump motor or solenoids, there is some reverse-biased current that flows back into the system.  Without any suppression circuitry (ie. “clamping” diode) and no reset-able fuses or anything, it eventually damages the board.  Each of these controllers was about $486.00 cost to us.  So eventually, we decided we could build our own better controller, and we could do it significantly cheaper using an Arduino-based solution.

So that is exactly what I did.  All the other controllers used a D-pad arrangement; Soft-membrane buttons for each direction.  I opted for a thumbstick because I felt it would be easier to water-proof (not necessarily true as it turns out) and would be easier to manipulate and potentially allow for finer-grained control of the plow.  So I went with Arduino Uno R3, a Sparkfun ProtoShield , and a SparkFun Thumb Joystick which I soldered to the protoshield.  The thumbstick is essentially just a couple of potentiometers (one for each axis) that act as voltage dividers.  I needed a way to read the analog values for both pots (axis) and then normalize the values to range from -100 -> 0 -> +100.  Naturally, I went looking for an Arduino library that could do this work for me.  I found a library that *almost* met my needs.  The problem with it was it did not process events immediately. Instead it would only emit a single event after processing all the possibilities.  So I decided to write my own library instead.  My library emits *all* events as soon as they are detected.

You can use it as described below.  The first thing you’ll need to do, is download and install the library.  Next, wire up a thumbstick to an Arduino like so:

joystick

 

(Note: You can use whatever analog inputs you want, I just used A0 and A1 as an example. However, you MUST use analog inputs.)

Now, you can calibrate it and start getting readings.  It is important to note that you should not touch the joystick while the sketch is starting up. The calibration process takes current readings from the stick and computes new center, stroke, and threshold values based on these readings.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "Arduino.h"
#include "JoystickLib.h"
 
Joystick stick(A0, A1);
 
void setup() {
   Serial.begin(9600);
   while(!Serial) {
      delay(10);
   }
 
   // Calibrate the joystick. For this to be effective, the joystick should
   // be resting at its center position.
   stick.calibrate();
}
 
void loop() {
   // Both axis values should be:
   // Center = 0
   // Farthest left (X) or farthest down (Y) = -100
   // Farthest right (X) or farthest up (Y) = 100
   // Or any value in between. Make sure you call loop() first.
   stick.loop();
 
   // Print the X-axis value.
   Serial.print(F("X = "));
   Serial.printlin(stick.getX());
 
   // Print the Y-axis value.
   Serial.print(F("Y = "));
   Serial.println(stick.getY());
   delay(500); 
}

You can also test what direction the joystick is in like so:

 

1
2
3
4
5
6
7
if (stick.isUp()) {
   Serial.println(F("Stick is up"));
}
 
if (stick.isDown()) {
   Serial.println(F("Stick is down."));
}

Or you can handle events. These events include: when the joystick moves in any direction including diagonals and does so in +1 or -1 increments (in other words, a movement of only +1 on the Y-axis would be considered an “up” movement) and when the joystick goes neutral (returns to zero on both axis). The method signature for the event handler callbacks do not currently pass any event objects, so it only needs to be a void:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
void printPosition() {
   Serial.print(F("X: "));
   Serial.println(stick.getX());
   Serial.print(F("Y: "));
   Serial.println(stick.getY());
   Serial.println();
}
 
void onUpHandler() {
   Serial.println(F("Direction: Up"));
   printPosition();
}
 
void onDownHandler() {
   Serial.println(F("Direction: Down"));
   printPosition();
}
 
void setup() {
   Serial.begin(9600);
   stick.calibrate();
   stick.onUp(onUpHandler);
   stick.onDown(onDownHandler);
}
 
void loop() {
   stick.loop();
   delay(300);  // Delay not necessary.  Just added to make it easier to read the output.  
}

Given the sensitive nature of the events, it may be best to determine a threshold value and then compare the axis value against it before reacting to it:

 

1
2
3
4
5
6
7
8
const int AXIS_THRESHOLD = 30;
 
void onUpHandler() {
   if (stick.getY() > AXIS_THRESHOLD) {
      // Do stuff only if the Y-axis is greater than 30.
      // This way we know the movement was more deliberate.
   }
}

For my application, I used event handlers and forced cardinal direction movement only, then fired one or more SSRs based on which direction the user was trying to move the plow. These SSRs, in turn, triggered solenoid(s) and the pump motor (except when lowering the blade) to allow the hydraulic fluid to move the arms.  You can increase or decrease the sample rate by using delay() inside your loop() method.  In the future, this will be option in the library itself.

Have fun and happy hacking!

Wednesday, December 2nd, 2015 Arduino, C/C++, Programming No Comments

Controlling a CrystalFontz 16×2 serial LCD with Arduino

While digging through a box of parts, I came across an old CrystalFontz 632 (16×2) intelligent serial LCD display.  With all the recent work I’ve been doing with Arduinos and Raspberry Pis, I thought it would come in handy.  Most LCD displays designed to work with Arduino require quite a few I/O pins (more than I’d care to sacrifice for most projects), so I thought a nice serial LCD would be a lot better since I could just use 1 or 2 pins and the SoftwareSerial library to control the display.

Like I said, this thing is pretty old.  I think I bought it sometime back in 2000 maybe.  I used to use it with some software package that had “driver” that talked to the display.  The software would monitor things like fan speeds, CPU speed, temperatures, utilization, etc and spit them on the LCD.  The software was unreliable and had to be constantly re-launched.  Eventually I got frustrated with it and gave up.  But I kept the display.  I found it with some light corrosion on the bracket it was mounted to and a serial cable still attached to it that had the end cut off.

I noticed the pin header on the back that is used to provide power indicated that it just needed 5V DC.  Hmmmm…. should be easy to test then.  So I took an old power supply hooked it up and…. voila!  The screen lit up and displayed its firmware bootscreen then cleared and displayed a blinking cursor.  Awesome.  I’m in business.

So I dug out an Arduino Uno and started writing a test sketch.  I honestly had no idea how to interact with this thing, but I just figured I could probably just start out by sending some text to it and see what happens.  No luck.  I sent “Hello, World!” using the print() method of the SoftwareSerial library and it just produced garbage.  At least it received the data I guess.

I tried using different BAUD rates to no avail.  Eventually, I realized that maybe I needed to send the data byte-encoded or I probably needed to send some kind of command to it before I could use it properly.  I noticed there are solder pads on it for an SPI connection and wondered if I’d have better luck using SPI instead.  I decided not to get ahead of myself, so I went to the CrystalFontz website, which as of this writing was still up.  Joy!  I was happy to see they were still in business.  And to my amazement, they still had specs and datasheets for this display.  So I downloaded the manual for the 632/634 series.  The only difference between the 634 and the 632 is that the 632 is 2 row, 16 column and the 634 is 4 row, 20 column.  Other than that, the command set is the same for both.  As I started reading the manual, I discovered that when using logic level serial (such as with the Arduino), there are some jumpers (well… solder pads) that need to be connected.  Specifically, I needed to close jumpers JPB (RS-232 data inverted) and JPE (DATA_IN is 0v to 5v swing).

So I soldered those 2 connections and tried again. BAM!  No we’re getting somewhere!  Then I realized that every time I restarted the Aduino, it appended the text to the previously printed text and ran off the display.  Yeah…. I gotta keep reading.  So I got to the section describing the command set.  As I assumed, they were all just byte values representing ASCII commands.  For example \0001 (or Control A) sends the cursor to it’s home position (upper left-hand corner or row 0, column 0).  So I tried some commands out and eventually got to where I could print text on both lines of the display, clear the screen, print some more stuff, turn the backlight on and off, etc.  I had a lot of fun experimenting with it, and then decided I could just write a library to do all the heavy lifting for me.

I googled around and searched github first, just to make sure I wasn’t trying to re-invent the wheel and didn’t find much on using the CrystalFontz displays with Arduino and more importantly, did not find any libraries written to do the work (although I did find a couple guys had worked with them and wrote some demo sketches).  So I wrote my library and some test sketches and tried them out.  It all worked beautifully!  So I decided to publish my library to github, but first I should probably test it in a live installation in a production environment.  That’s when I ran into problems.

It all worked fine until I installed the library into the actual Arduino libraries folder and tried to run a test sketch.  I got a bunch of weird compiler and linker errors.  So I googled around and came across this post and this article and came to the conclusion that because of the “Arduino Magic” and the way the linker works, you have to include BOTH my library and the SoftwareSerial library in order to get your sketch to compile EVEN THOUGH the SoftwareSerial library is already included in mine.  Lame.

Aside from that caveat, it is a pretty robust library and provides almost the entire functionality of the 632/634 command set including drawing bar graphs, controlling brightness and contrast, scrolling, wrapping, etc.  And the best part is, you can control MULTIPLE displays from a single Arduino.  You only need a single I/O pin for each display (2 if you also want to control the backlight).  You can get it here.

It has low memory usage (estimated 128 bytes), but is a whopping ~5K in size, so keep that in mind if you are working with a large sketch and are pressed for space.  Of course, you can always just fork the library and strip out the parts you don’t need if you need to reduce its footprint.

 

Enjoy!

Monday, July 21st, 2014 Arduino, C/C++, Programming No Comments

Arduino IDEs part 2

So I was reading this post the other day when I was trying to determine why one of my Arduino sketches was puking out garbage on the serial port.  It was a good read, and I definitely recommend you go read it too (particularly if you are an advanced Arduino programmer).  I had no idea how flawed the Arduino core libraries were.  So I went digging through the source code (why the hell hadn’t I done this yet?).  Sure enough…. yeah…. needs work.  Things have indeed improved since Alan’s post was originally written.  But, as he pointed out, the hardware serial library still needs fixing (among other things).  Nonetheless, it got me thinking…. maybe I need to “graduate” bit in Arduino-land.  So while I was googling around and reading all kinds of forum posts and talking to people on IRC, etc, one of the common things people kept talking about is just using ATmel Studio and doing direct pin access.

I had stayed away from Atmel Studio because event though it is designed to program Atmel AVR chips (which is what the Arduino platform is built on), it is not specifically geared toward the Arduino platform, and more importantly, it is essentially customized version of Microsoft Visual Studio…. thus, it is not cross-platform compatible.  In my previous post, I discussed my preferences when it comes to Arduino IDEs and the importance I place on cross-platform IDEs.  While looking into the Atmel Studio 6.1, I was reading up on the Atmel Gallery and decided to go check it out and see what kind of add-ons were in there.  Wouldn’t you know…. right on the front page was the Arudino IDE for Atmel Studio.  You know what?  This thing is BAD ASS.

I know, I know, I know…. “But it only works on Windows!”.  Yes… unfortunately, this is still true.  But I gotta tell ya… I think I like it better than Visual Micro.  If you’re a Windows user, or at least aren’t as anal about platform compatibility as I am, then you’re gonna love it.  I’ve only gotten to use to write one sketch (a BIG one) and edit a couple others, but so far…. it’s fairly superior to almost everything else I’ve used (so far).

Tuesday, December 31st, 2013 Arduino, C/C++, Programming No Comments

A Better Arduino IDE

Been a long time.  My professional duties and chaotic life have precluded me from things like blogging for a while now.  But since I’m on vacation, time to catch up!

So I’ve been questing for a better Arduino IDE.  I really enjoy the Arduino in its various forms, but I find the IDE rather lacking….. and I’m not the only one.  It seems to be a rather popular search.  Everyone is looking for something better.  I’ve seen some different forks of the standard Arduino IDE, but they all just seem to add additional hardware support or a couple small features.  None of them make the IDE (specifically the editor) any *better*.  Being a guy who spends much of his time in either Microsoft Visual Studio or Eclipse, using the standard Arduino IDE leaves me wanting more.  Sure, it is perfectly fine for beginners, but for professionals or more advanced users, it seems lackluster.

So I began my quest.  The first thing I ran across was MariaMole.  It is a much better IDE, but as of this writing, it only runs on Windows (Linux and MacOS support planned).  Also, I don’t care of the default color scheme (although still better than Arduino IDE) and I could not find an easy way to change it.  But the killer is not being (currently) cross-platform.  I develop on Windows, Linux (Mint) and MacOS X.  So I need, if possible, an IDE that can run on all 3.

Then I came across Visual Micro.  Let me get this out of the way: I LOVE Visual Micro.  It is hands-down the best IDE I’ve used for Arduino development so far.  Except for one problem: It only works on Windows.  This is because it is a Visual Studio add-on.  That in and of itself isn’t bad (because I love Visual Studio), but not being cross-platform is.  For a while, I was doing all my ‘serious’ Arduino development in Windows using Visual Micro, then just using the standard Arduino IDE on Linux and MacOS X.

Then I thought, “Hey… I bet there’s an Eclipse plugin out there for this”.  Sure enough, there is.  At first, I read these instructions and thought, “This seems like a lot of work”.  Then I saw the link for the actual plugin.  I ignored the fact that the documentation kept referencing old versions of Eclipse (as of this writing I’m using ‘Keppler’ everywhere) and proceeded to install and configure the plugin.  Still not terribly simple, but I get to use a cross-platform IDE of choice.  Also, it does not support *.ino files.  Instead, it produces ‘main.h’ and ‘main.cpp’ files.  This sucks if you need to be backward compatible with the Arduino IDE.  Also, it was fairly buggy and more often than not, I either could not get my source to build or could not get it to upload.  I read tons of stuff in forums, etc and plenty of people suggested various fixes to my various problems, but ultimately I gave up.  If I have to invest that much effort into my tools (especially on 3 platforms), then I just go find a better tool.

So I kept searching.  I eventually came across this article describing using QtCreator for Arduino development.  Fireworks went off in my head.  “OF COURSE!!”, I thought.  QtCreator is *built* for C/C++ dev and supports templates, etc.  And it’s cross-platform! I love QtCreator as an IDE in general, so I got really excited.  I went off and downloaded the latest build of QtCreator and Qt5.  I also found a QtCreator project template for Arduino here.  Even though, the documentation seems a little dated, it worked just fine.  There are some caveats: First, like the Eclipse plugin, the project template creates *.h and *.cpp files instead of a *.ino.  I chose to rename the *.cpp file to *.ino, which QtCreator is still happy to open, and then I just include it in the *.h file.  This method is also supported by the Arduino IDE, because if it finds a *.h file with the same name as your *.ino file, it opens them both in separate tabs in the editor.  I then adjust my paths depending on what platform I’m compiling on using #defines (see an example on my github page here).  I also had to create separate *.includes files for each platform.  But hey, minor tweaks to get to use a beautiful IDE.  One problem, compile/upload functionality is a bit sketchy.  Most of the time, I can get it to compile, but I usually can’t get it to upload.  So I started using QtCreator to do all the work, and then just used the Arduino IDE to compile and upload, and also for the serial monitor.  Still not quite an ideal solution.

A co-worker asked me what IDE I used for Arduino development and I pretty much gave him all the options I just laid out for you.  He decided to go the QtCreator route also.  But his inquiry renewed my quest.  So I went looking again.  That night, I stumbled across a single mention of something called ‘Stino’ in a forum post.  I decided to go look.

It was wonderful.

As it turns out, Stino is a plugin for Sublime Text.  I had never heard of either.  This was a new experience, and I was not disappointed.  I followed the instructions and went and downloaded Sublime Text 3.  Next, I enabled package control.  Then, using the package manager, I downloaded and installed ‘Stino‘.  And guess what?  Its cross-platform!! I opened existing projects on all 3 platforms and was able to compile and upload without any alterations.  In fact, the Stino plugin basically provides all the existing functionality of the Arduino IDE (including serial monitor) and is every bit as simple to use, but with a MUCH better code editor.  It supports color themes, syntax completion, etc.  It even has console output for the compile/upload process just like the Arduino IDE.  And…. it natively supports the *.ino format and uses that by default when creating projects.

I’m a fan-boy, to say the least.  Not gonna lie.  As much as I love QtCreator, I find Stino + Sublime Text 3 to be the best (cross-platform) IDE so far and I now do ALL my Arduino development using it.  Plus, since the projects it creates are basically regular Arduino projects, they are directly compatible in both IDEs.

For the life of me, I can’t figure out how there hasn’t been more buzz about this.  So…. I recommend you at least give it a try.

That being said, I’m going to get back to slinging code myself.  I’m currently working on a Christmas light controller using an Arduino Uno R3.  More on that soon!

Monday, December 23rd, 2013 Arduino, C/C++, Programming No Comments

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.

Cheers!

Wednesday, April 3rd, 2013 Arduino, C/C++, Programming, Raspberry Pi No Comments

Arduinos!!

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!

Caveats:
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.

Tuesday, February 12th, 2013 Arduino, C/C++, Hardware, Programming, Raspberry Pi No Comments