Great news for STM32 firmware engineer

I’m about to start a new project using STM32F4x ARM Cortex M4 from ST Micro. I was planning to maybe get Keil uVision 5 since most of my training had been done using Keil. I have explored other options like a bunch of GNU tool chains and such but found them to be really annoying to put together and many times don’t work real well especially with ST ARM devices. I came across Atollic TrueStudio Lite a while back and I really like it. All my codes that were written in Keil uVision 5 compiled with no issues using TrueStudio. I first started looking at Keil uVision 5 pricing and it’s $5k for a node lock perpetual license or $9k fro a perpetual floating license. Maybe I could convince work to buy the license, but after spending 17K on Altium Designer license and subscription I don’t know whether I could get Keil license too. Fortunately, I went to Atollic website again to see how much a TrueStudio Pro would cost. I found this news announcement:



http://blog.atollic.com/early-holiday-gift-from-stmicroelectronics

Basically, it said that ST Micro just acquired Atollic and they’ll make TrueStudio Pro FREE!!! Wow!  I can’t wait to try the Pro version since the Lite version was pretty good (except for the annoying long loading splash screen at the beginning).  Some people might say the TrueStudio is still technically a GNU compiler and Keil would be a better tool.  Nevertheless, I don’t think you can beat a free professional tool.  Even TI made their Code Composer Studio free a while back which actually annoyed me because I did pay for the license just a couple months before they made it free.  I did consider using MSP432 since it’s also an ARM device, but you don’t have the freedom to clock it to 400 MHz like you can with ST ARM devices.  The STM32 Cube tool was decent but it’s annoying without having a decent IDE to use it with. As I mentioned before, I tried to roll my own GNU tools, but the success of compiling the codes from STM32 Cube was questionable without a lot of manually fixing a lot of things.  It works well with Keil and TrueStudio right out of the box though. Now I can see an even better integration between ST software and TrueStudio going forward.  Maybe they’ll bundle STM32 Cube already inside TrueStudio and it’ll be a one-click code generation.  That would be incredible.

Free good professional software is the name of the game these days.  That’s really the reason why I picked Atmel products over Microchip 10 years ago.  Atmel has Atmel Studio which was a quality C GNU compiler tool for free while Microchip charged you a lot of money to use their C compiler.

In any case, looks like I have a perfect solution for my ARM Cortex M4 project.

kivy and Python 2.7x On Windows (And Using Pip To Install Wheels)


I have been tinkering with GoLang for a while and haven’t been using  Python until today I came across a very interesting Python framework called kivy (“Kee-vee”?)  It’s a very nice frame work that runs OpenGL with accelerated hardware to give you a smooth graphical user interface.  It also allows multi-touch for inputs.  It claims to be able to deploy on any platform including Android.  That’s very cool!.

However, I ran into trouble quickly when I realize that I need Cython and other packages to use kivy.  My development environment is in Windows (I know I should use Linux, but we use Windows at work so I want to stay compatible with work).  Normally this is not a problem since I can go to my favorite Windows Binaries for Python Extension Packages webpage maintained by Mr. Christopher Gohlke.   He pretty much has everything you can think of for Windows binary packages.  It’s a lot cumbersome for me to go hunt down the Python sources for these packages and try to do the Python install myself.  It’s so much easier to go to a one stop shop like Mr. Gohlke’s page and just install the packages I want. The trouble is the page is now using Wheel files instead of the EXE files for the packages. This requires using PIP to do the installation and I have no idea at first how to do that.  Well, let me share with you what I found so that you can save time and frustration that require to use this amazing page of Python packages.

Install Python
I’ll make the instruction as a brand new Python install.  I chose Python 2.7.13 (32-bit) since it’s the latest 2.7.x as of the time of this writing.  I didn’t pick Python 3.x because we use Python 2.7.x at work and again I want to be compatible with work.  Someday I’ll try Python 3.x but so far many libraries are in Python 2.7.x and not everything has migrated over to Python 3.x yet even though it’s been almost like a decade since Python 3.x came out (2008 I think).  This instruction should technically work for any versions but you just need to make sure you match the packages with the version you are using.  For me, it’ll be 2.7.x and 32-bit for all the packages.

Now you need to make sure you have Python in you windows path variable or you can’t call python.exe from anywhere in the command line. Click Start Menu and type into the search box “Edit the system environment variables”.  Click on the option that showed up in search under Control Panel result.

Now click on the “Environment Variables …” button under the System Properties screen that showed up.

Click on the Path variable under System variables.  You might have to scroll down if you have a lot of stuff in your System variables like I do.  Then click “Edit …”


For Windows 10 (with Anniversary update), Microsoft kindly added a new easier to read screen for the path variable management.  If you have a different version of Windows, you’ll have to look through the long line of paths separated by semicolons (;).  To add path, just add a semicolon to the last path in the line and then type in the new path you want.  For Windows 10, just click on “New” button to add path variables.  Add the following paths (defaulted by Python 2.7.x install.  If you install python in a different folder, you’ll have to use your custom path):

C:\Python27
C:\Python27\Scripts

Now that the difficult part is done, time to move on to PIP install.

Download and Install PIP
This page shows you how to install PIP but I’ll explain how I did it.  Basically, right click on get-pip.py and save it to some folder.  I put it in a C:\python_packages\ where I collect my packages to install.

Launch a command prompt (Click start button, type “CMD” into the search box and hit enter.).  Get to the directory where you keep the get-pip.py then type:

python get-pip.py

If you correctly setup your path variables as I explained in the previous section then this should execute a pip package download.  Once this is done, you are almost ready to be able to use the Python wheel packages.

Install Wheel Requirements to Use Mr. Gohlke’s packages
Scroll  down and look for Pip package then download pip-9.01-py2.py3-none-any.whl from Gohlke page into any folder.  I recommend using the same folder where you put the get-pip.py script.

[Update 4/21/2017]: You can get PIP wheel from Python Package Index as well.  It’s a bit faster to download than Gohlke page.  Download the

If your command prompt is still there and you are still in the same folder, you can type the following command:

pip install python.exe pip-9.0.1-py2.py3-none-any.whl/pip install pip-9.0.1-py2.py3-none-any.whl

It should say something about the requirement is installed. If it doesn’t come up with error then you are good to go.

Installing Cython
Since we have PIP installed and requirements met, we can try installing a package from Mr. Gohlke’s page.  Let’s try installing Cython since we’ll need that for Kyvi.  Look for Cython-0.25.2-cp27-cp27m-win32.whl or whatever the latest version would be for Python 2.7.x and 32-bit.  Click on the link and you’ll be prompted for a save file location.  Again, I’ll put the package into the same folder we have been working with.  Kudos to Mr. Gohlke, The page is pretty well organized and kept up-to-date.  You can see from the file name what Python version and Windows version you need.

Launch a command prompt again and navigate to our C:\python_packages folder. Type the following command to install the Cython package:

pip install pip install Cython-0.25.2-cp27-cp27m-win32.whl

You should see this message if everything went well:

If you get an error saying that pip is unrecognized then you need to make sure that you have the path C:\Python27\Scripts in your path variables.  Also make sure to close your command prompt and relaunch it any time you updated your path variables.  The command prompt doesn’t know about the new variables until you restart it.

The generic command for installing any packages is just:

pip install SomePackage.whl

That’s it for installing Windows Binary wheels!

Installing Kyvi
Let’s finish installing Kyvi now that we have Cython installed.

First make sure that we have the latest pip wheel and setup tools using the following command:

python -m pip install --upgrade pip wheel setuptools

Install all the dependencies required to run Kyvi:

python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew

*Install gstreamer:

python -m pip install kivy.deps.gstreamer

You could use a command line, but I kept running into a memory error issue maybe due to it being a large file (121 MB) and my firewall and anti-virus program so I just went to the PyPI site to download the wheel.  I downloaded the appropriate version for my Python 2.7, 32-bit. ( kivy.deps.gstreamer-0.1.12-cp27-cp27m-win32.whl).  Once the file is downloaded to our usual location, run pip install:

pip install kivy.deps.gstreamer-0.1.12-cp27-cp27m-win32.whl

There shouldn’t be any error messages if everything went well.  Finally, install kivy itself:

python -m pip install kivy

Now let’s run an example python script using kivy to make sure that we have successfully installed kivy.  In command prompt, type in this command:
c:\Python27>python c:\python27\share\kivy-examples\demo\showcase\main.py

If everything was installed correctly, you’ll see a brief script execution in the command prompt and you’ll be greeted with the hello world demo:

Now it’s time to have fun using kivy for your GUI.  I find it to be much prettier than Tk and much easier to use than Qt.  There are a lot of resources from kivy.org.  Here’s the link to building your first example app in kivy.

Time To Move To KiCad EDA

I just found out recently that AutoDesk just bought CadSoft Eagle — my favorite PCB layout software.  I have built many boards and libraries using Eagle starting from version 4 all the way to version 7.7.  Now I just found that CadSoft Eagle is no more.  AutoDesk owns Eagle now and they have a subscription only purchase model.  This is terrible in my opinion since you used to be able to just pay once and own the software.  Now this try-and-fail method of DRM is going to make the new Eagle fail just like any software that had done this before it.  My prediction is that only companies that can’t switch to a different software package and software pirates would be using Eagle.

This brings me up to the next point — switching to a different package.  I played around with many packages including Altium but that software is out of reach unless you work for a company with deep pockets.  In the past around 2013, I looked at KiCAD and it was a terrible hodgepodge of many pieces of software bolted together with awkward usage.  I didn’t even want to touch it seeing how much work it would be just to even get it going.  Then I looked at it again last year (2016) and I was surprised how amazing and polished it has become.  It’s on the same level as the new Blender and Inkscape software packages.

It’s time to give it another shot and see whether it’s going to be my new EDA program of choice. Here is the link to KiCad if you want to start the switch too!

Here’s a nice beginning tutorial for KiCad from ContextualElectronics

 

Controlling Arduino Nano with a Golang Webserver

Recently I have been obsessed with Go Programming Language (Golang) from Google.  It’s such a lovely tool for any programmers that want simplicity of Python but a raw power of a compiled C program.  Also, let’s add put it on steroid with a native concurrency support.  This is the power of Go.

Since you can easily just learn how to do the “Hello World” programming in Go yourself, I’m going to introduce something that would normally be difficult to do using other language and platform.  I’ll demonstrate how to build a simple web server to hand various request in the address to toggle the LED on, off, and blink on an Arduino Nano board hooked up to the web server computer.  I’ll be working with Windows version of Go.  Some minor change can be made to use the code in Linux.

The first thing to do is install Arduino IDE if you don’t already have one on your computer. I’m running version 1.8.1 which is the latest one as of this writing. You’ll also need an Arduino Nano if you want to follow this example exactly.  Otherwise, any Arduino board should work as long as it can be programmend with Firmata protocol and you know which pin is the LED pin.  If you want to support Arduino, you can buy the genuine version from many electronics vendor like Mouser here in the US for just under $30.  Arduino Nano could also be cheaply purchased on Ebay for under $5 with free shipping.  The reason why it’s so cheap on Ebay is because most of the components are probably fake.  If you don’t want to run into problems with FTDI bricking your cheap Arduino Nano, I’d suggest getting the version that uses CH340 as the serial to USB IC.

The Nano needs to be flashed with Firmata protocol.  This can be easily done via Arduino IDE.

Connecting to Arduino Nano using Arduino IDE

Launch Arduino IDE and then go to Tools -> Board.  Select Arduino Nano or whatever board you are using from the list.

Pick the correct processor for your Nano board.  In most cases, it’s ATMega328.  If you are not sure just look at the chip on the Nano.  For the one I have it says MEGA328P on it.

Now select the proper COM port where your Nano is connected.  In my case, it’s COM8.  After this is done, the next thing to do is load Firmata protocol into our Arduino Nano.

Uploading Firmata Protocol to Arduino Nano

We can load Firmata example into our Sketch window by going to File -> Examples -> Firmata -> StandardFirmata

Now you should see a pretty long sketch for StandardFirmata.  You can read through the codes if you are interested.  Several of people put their time and effort into making this available for free.  I love open-sourced community.  Anyway, check the lower right bottom of Arduino IDE to see whether you have the correct connection information to your Nano.  Click on the right arrow button on the top menu to program the firmware into your Arduino Nano.

If everything works, then you should see “Done uploading.” message.  Now your Nano is ready to be controlled by Go Webserver.  Close out Arduino IDE or you’ll prevent COM port on the Nano from being accessible.

I’m not going to cover Go installation in this post, but it might be a topic for a future post since I have already made some slides for work on how to install and use Go.  I’ll have to transfer the content here for public use.  I’ll assume that you already have Go ready to use on your system.  I use LiteIDE as my preferred Go Programming IDE.  It’s very stable and has all the features a paid program like WebStorm has.

Gobot.io Package Installation

We require the use of gobot.io library to interface with Arduino Nano.  To install go bot, in command prompt, type in this command

$ go get -d -u gobot.io/x/gobot/...

It’ll look like your command prompt stopped responding, but give it a minute to finish the installation.  Once it’s done, you’ll see a new command prompt line.

Go Programming Web Server Example

Before we start playing with the Nano, let’s run the webserver example provided by Golang.  This code will create a web server on your local machine listening to port 8080.  Anything you type (web safe string) after / symbol will be shown in the greeting string.

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Gobot.io LED Toggling Example

Now let’s do the example provided by Gobot.io to toggle our LED on using their example code.
First you just have to make sure to import the gobot libraries in your Go code.  For our example, we’ll only need to use the GPIO and FIRMATA libraries.

  
import (
	"gobot.io/x/gobot/drivers/gpio"
	"gobot.io/x/gobot/platforms/firmata"
)

Here’s the example LED toggling code from gobot.io.  There were a couple of examples, but I found that the firmata_blink_metal code gives you the most direct control of the hardware.

package main

import (
        "time"

        "gobot.io/x/gobot/drivers/gpio"
        "gobot.io/x/gobot/platforms/firmata"
)

// Example of a simple led toggle without the initialization of
// the entire gobot framework.
// This might be useful if you want to use gobot as another
// golang library to interact with sensors and other devices.
func main() {
        f := firmata.NewAdaptor("/dev/ttyACM0")
        f.Connect()

        led := gpio.NewLedDriver(f, "13")
        led.Start()

        for {
                led.Toggle()
                time.Sleep(1000 * time.Millisecond)
        }
}

This won’t work right off the bat if you are running a Windows Go on a Windows machine as I do.  The reference to COM port has to changed to “COM8” for my Nano to get it to work. The LED pin is 13 on the Nano so that doesn’t need to change.

        f := firmata.NewAdaptor("COM8")

You should be able to play around with this code to toggle your led on and off using other commands like led.On() and led.Off()

Merging the Codes Together

Now the hard part is trying to merge the 2 examples together.  This is not as straight forward as I initially thought since I didn’t want to re-open the COM port every time a new command is sent because there’ll be a delay and the Nano seems to reboot every time you reconnect to the COM port. To prevent that from happening, I need to be able to open the COM port at the beginning of the program and then just pass the reference to the COM port to the http handler.  I didn’t  know how I could even do that since I’m still new in using Go and there wasn’t any good examples on Gobot on how to do things outside the main function.   It took me a while to figure out how to solve this sending the firmata.Adaptor object to the http handler issue.  After doing some web searches, I came across this post that suggested using closure to pass the parameter to the http handler.  The answer was passing a string, but I figure that maybe you could pass the pointer reference to the firmata.Adaptor like this:

func handler(w http.ResponseWriter, r *http.Request, f *firmata.Adaptor)

Amazingly, it worked!  So after initiating the COM port and assign it the variable f, I can now pass it to the http handler using the closure technique.

	f := firmata.NewAdaptor("COM8")  //for Linux use ("/dev/ttyACM0")
	f.Connect()

	led := gpio.NewLedDriver(f, "13")
	led.Start()
	led.Off()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		handler(w, r, f)
	})

Here’s the complete Go code.

package main
import (
     "fmt"
     "net/http"
     "strings"
     "time"

"gobot.io/x/gobot/drivers/gpio"
"gobot.io/x/gobot/platforms/firmata"
)

func handler(w http.ResponseWriter, r *http.Request, f *firmata.Adaptor) {

     text := r.URL.Path[1:]
     text = strings.TrimSpace(strings.ToUpper(text))
     led := gpio.NewLedDriver(f, "13")
     command := "UNKNOWN"

     if text == "LED_ON" {
          command = "turning LED ON."
          led.On()
     } else if text == "LED_OFF" {
          command = "turning LED OFF."
          led.Off()
     } else if text == "LED_TOGGLE" {
          command = "toggling LED."
          for i := 0; i < 10; i++ {
               led.On()
               time.Sleep(time.Millisecond * 250)
               led.Off()
               time.Sleep(time.Millisecond * 250)
          }
     } else if text == "EXIT" {
          command = "suggesting that you just close the browser window to exit."
     } else {
          command = "confused about what you want. Please send a new command."
     }
     fmt.Fprintf(w, "Nano is %s", command)
}

func main() {
     f := firmata.NewAdaptor("COM8") //for Linux use ("/dev/ttyACM0")
     f.Connect()

     led := gpio.NewLedDriver(f, "13")
     led.Start()
     led.Off()

     http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
          handler(w, r, f)
     })
     http.ListenAndServe(":8080", nil)
}

Now you can go to the web server and type

localhost:8080/LED_ON   to turn on the LED
localhost:8080/LED_OFF   to turn off the LED
localhost:8080/LED_Toggle   to make the LED blink 10 times

Any other command, the message will just complain about not understanding your command.

That’s it! I hope you enjoyed Go Programming and Arduino Hardware interfacing in this quick example.  There are many possibilities that you can expand this code to do more interesting stuff.  I’ll also play with ESP8266 so that we can do some cool wireless IoT with Go.

Installing YouTube-DL on Windows Subsystem for Linux (WSL)

Please read my previous post on how to enable Windows Subsystem for Linux (WSL) on Windows 10.  You must have the Windows 10 anniversary update installed since WSL is not available on the original Windows 10.

Youtube-dl is an awesome downloader for multimedia from the internet using a simple command line.  You can encode the video into a different format as well (namely FLV and MP4).

Since Windows System for Linux doesn’t automatically install Python which is required for Youtub-dl to work correctly, you need to first install Python.  You can install either Python 2.7x or Python 3.x.  I installed Python 2.7x since most libraries are more compatible with it.  To install Python 2.7x, open up your Ubuntu Bash window, and type in this command:

sudo apt-get install python

If you are adventurous and want to try Python 3, then use this command:

sudo apt-get install python3

In the past when I tried having both versions, there are conflicts when trying to run Python codes. So I just pick one version and stick with it. I recommend using 2.7x for stability and comparability. Eventually Python 3 will be the best version but maybe give it a couple more years.

There are many ways to install youtube-dl, here are the 2 common ways:

Using apt-get
Open up your Ubuntu Bash window, and type in this command:

sudo apt-get install youtube-dl

After the installation is done, run an update

sudo youtube-dl -U

Using Pip
First you have to install Pip

sudo apt-get install python-pip python-dev build-essential 
sudo pip install --upgrade pip 
sudo pip install --upgrade virtualenv 

Now you can install youtube-dl with pip using this command:

sudo pip install youtube_dl

Then upgrade with Pip

sudo pip install --upgrade youtube_dl

If you try to do a video download (Master of the House song from Le Miserable) from youtube, you’ll get a bunch of errors.

sudo youtube-dl -o LeMiserableMasterHouse.MP4 "https://youtu.be/TWlzFbmZZHU"

From searching the web, I found that we need to do a bunch of permission settings to get the downloader to not error out due to things like Protocol error and such. Use this command first:

sudo curl -L https://yt-dl.org/latest/youtube-dl -o /usr/local/bin/youtube-dl

Then set permissions:

sudo chmod a+rx /usr/local/bin/youtube-dl

Now you shouldn’t have problem downloading videos from youtube. The video is downloaded to the directory where you issues the youteb-dl command. You can supply the extension of the file to be .FLV or .MP4 when downloading.

For more details on the commands and options for youtube-dl, please visit this URL:

https://github.com/rg3/youtube-dl/blob/master/README.md#readme

Enjoy downloading YouTube videos!

Enabling Ubuntu Bash on Windows 10

A quick reminder that this feature is only available on Windows 10 (with the latest update). It’s still a beta feature but the developers have fixed many of the bugs and it’s pretty stable.  Hopefully more features will show up in the future to allow us to run more functions closer to the real Ubuntu.

Click the Start button and type in the search “For Developer Settings”.
Choose “Developer mode”.  Windows might prompt for a permission.  Allow it to proceed.

developer settings

Again, click on the Start Button, type into the search “Turn windows features on or off”
search turn windows feature on

Windows Features screen will show up.  Scroll down to find “Windows Subsystem for Linux (Beta)” option and check it.

enable subsystem

Click OK.  Windows will ask to re-boot.  Go ahead and reboot your system.

After computer restarted, click on the Start button and type in search “bash”.  Select bash.exe from the search result and run it.

A command prompt like window will appear.  It’ll ask you to type “y” to proceed.  Type in “y” and wait for the download of the Ubuntu to proceed.

Ubuntu download

Once the install is done, go back to the Start button and type in search “Bash on Ubuntu”. You can pin the program to the task bar or start menu for a later easy access.

start menu

My start Menu looks different from the standard Windows 10 start menu because I prefer Windows 7 style menu.  I highly recommend Start10.  It’s a paid app for $4.99 but I think it’s worth it.  https://www.stardock.com/products/start10/

There are other ways to customize the start menu bar using free software but it’s a topic for a different blog post.

Now that you have Ubuntu Bash install, you can use it just like a normal Ubuntu terminal.  Most of the commands work as long as it’s not server or graphical related functions.  The best thing I found is the use of grep which Windows needed badly and now we have it!

Bash on windows

Another awesome use is installing Go on here.  You could do Go on Windows already, but this moves it closer to the Go programming as it was intended.

A good thing to do is to run the update so that this is up-to-date. Use -y so that it says yes to everything or you can leave it out and individually confirm each download:

sudo apt-get update -y

Launching Python Script when Raspberry Pi Boots (Console & Desktop Start)

We have been thinking about using Raspberry Pi 3 as our computer to control all the test equipment at work.  One idea is to use Python to control our equipment (like FTDI devices mentioned in the previous post).   So this got me thinking about how I could get a Raspberry Pi to launch the program when it first boots up.  After reading a bunch of posts on the wild wild internet, I came up with some ways to do this.


Console Mode Python Scripts Only

First, we need to make sure that we start up in the console mode rather than the X-window because the python script wouldn’t be executed from the console in the GUI mode. You could do this either by setting the Start X-server after boot to disable via

$ sudo raspi-config

Choose option 3 (Boot Options) to choose the boot environment.  To boot to console and login automatically use option B2 (Console Autologin Text console, automatiaclly logged in as ‘pi’ user)

Second, we need to be able to launch a python script right when the Pi boots up.  This is easy enough to do.  You just have to modify the profile file on Pi

sudo nano /etc/profile

Scroll to the bottom of the file and then add a script that you want to launch. In my case, I want to launch a python script called startupScript.py from my /home/pi directory.

sudo python /home/pi/startupScript.py

Now to test this, we can create the startup script and see whether it gets executed at boot time. Create our startupScript.py by using nano.

$ sudo nano /home/pi/startupScript.py

Here’s just a simple python code to go inside startupScript.py to display text:

#!/usr/bin/python
print "**********************************************"
print "*  This is a start up test script inside     *"
print "* /home/pi/startupScript.py                  *"
print "* Other python script can run at start up    *"
print "* by editing /etc/profile                    *"
print "**********************************************"

Save the script and then initiate a reboot on the Raspberry Pi:

reboot

When Pi boots back up again you can see that our python script got executed and the text message got displayed right before the console.


Qt4 GUI Python Scripts

Now what if we want to run the scripts with GUI?  Obviously this is problematic if the GUI requires to have X-window running.  Qt4 script would need this so we need to start from the X-window mode.   We can re-enable this with raspi-config again or use the command:

$ sudo update-rc.d lightdm enable

This time choose the B4 option (Desktop Autologin Desktop GUI, automatically logged in as ‘pi’ user.  When being asked to reboot, say no for now so that we can add some startup scripts.

Remember to remove the python script being launched in /etc/profile since that’s still enabled.

To use PyQt4, we need to first install it in our Raspberry Pi. The -y parameter at the end of each command automatically answer yes to any prompt during install so we don’t have to type yes each time to continue the installation.

$sudo apt-get install python-qt4 -y
$sudo apt-get install pyqt4-dev-tools -y
$sudo apt-get install qtcreator

We should now have everything we need to make a python Qt4 program. Let’s create a generic Qt4 program that just shows a blank GUI window. I’ll call this render.py and I’ll save it in /home/pi folder.

sudo nano /home/pi/render.py

Here’s the code for render.pi:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui

def main():

    app = QtGui.QApplication(sys.argv)

    w = QtGui.QWidget()
    w.resize(250, 150)
    w.move(300, 300)
    w.setWindowTitle('Simple')
    w.show()

    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

You can try running this script on the desktop and you should see a blank window showing up. Now let’s see if we can just launch this program when our GUI desktop first starts up.

To launch the script at startup, modify the /etc/xdg/lxsession/LXDE-pi/autostart would work.

First edit autostart file:

$ sudo nano /etc/xdg/lxsession/LXDE-pi/autostart

Add the following line at the end to launch your PyQt4 script:

@sudo python /home/pi/render.py

Save the file and exit.  We need to make sure the file permission is correct so that it can auto-launch.

$ sudo chmod +x render.py

Now we can reboot and when the Desktop starts again, our render.py program should be automatically launched.  If you want to make the program be something like a Kiosk mode that takes up the whole screen, substitute the line w.show() with w.showFullScreen().

Here’s the updated code to do the Kiosk mode:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui

def main():

    app = QtGui.QApplication(sys.argv)

    w = QtGui.QWidget()
    w.resize(250, 150)
    w.move(300, 300)
    w.setWindowTitle('Simple')
    w.showFullScreen()

    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

This code doesn’t include a good way to exit the program so the full screen mode will be stuck. Click Alt+F4 to terminate the program (just like Windows!?!?).

*Note on the new image of Jessie that comes with PIXEL desktop, the Pixel Version of Desktop seems to use a different start up file. We need to edit /home/pi/.config/lxsession/LXDE-pi/autostart instead.

$sudo nano /home/pi/.config/lxsession/LXDE-pi/autostart

Add the the same line to the bottom of the file

@sudo python /home/pi/render.py

Now when you reboot, it should launch our render.py program.

Using Raspberry Pi (Model B+) to interface to FTDI devices

I have always used Windows computers to interface to an FTDI based USB devices I built. Now due to the low cost and great availability of Raspberry Pi modules, it makes sense to see whether I could use a Raspberry Pi to talk to my FTDI based USB devices.

I have several Raspberry Pi Model B+ available from previous projects working on cluster computing and from my general hoarding of Rasberry Pi modules.

Googling the internet is the first thing I try to learn more about how to create an interface from Raspberry Pi to an FTDI device.

I found 2 ways: 1) Use PySerial and 2) Use pyLibFTDI. I’ll talk about both methods since they are both useful.

*Note:  I’ll use ‘$’ in command line to show that it’s in the console terminal and if there’s no ‘$’ then it’s a python code.  Don’t type $ in the console or the command won’t run.

PySerial Method:
This method is pretty straight forward since Raspberry Pi should already come with PySerial installed.  If not, run the install with the command line:

$ sudo apt-get install python-serial

Once the installation is done, you can launch into python by typing

$ python

You can also write a python file and just run it using the command below where <myfile> is your file name.  There are many text editor in Raspberry Pi, but I normally use nano.  I’ll talk about this later when you have to create a rule file.

$ python <myfile>.py

In order to figure out all the serial devices attached to your Raspberry Pi, you can run the following codes in Python.  I’m using Python 2.7 by the way.

import glob
ports = glob.glob('/dev/tty[A-Za-z]*')
for port in ports:
  print(port)

You might see a listing like this:

/dev/ttyUSB1
/dev/ttyUSB0
/dev/ttyprintk
/dev/ttyAMA0

Now you can interface to your device using the proper named port from the list.  My USB device is the ttyUSB0.  The ttyAMA0 is the GPIO serial port that you can actually use to to communicate to Raspbery Pi via serial via your computer.  You can google more about using ttyAMA0 if you are curious since I won’t cover that here.

import serial
ser = serial.Serial ("/dev/ttyUSB0")    #Open named port 
ser.baudrate = 9600                     #Set baud rate to 9600
ser.write('command\r')                  #send command string 
ser.read(ser.inWaiting())               #read data in read buffer
#You could also use ser.readline() to read but need to know # lines.
ser.close()

You can refer to PySerial API website to get all the commands and various things you can do with PySerial.

pyLibFTDI Method:
This is another way to interface to a USB device but you need them to be an FTDI device to work.  The nice thing about this method is the speed and reliability of the communication due to the use of FTDI’s own driver to talk to the device.  You can even bitbang the port using this method.  I’m not covering that topic, but you can find more details on pyLibFTDI website.

To use pyLibFTDI in Raspberry PI, you first need to install LibFTDI by running the following command:

$ sudo apt-get install libftdi-dev

After that is done, install pyLibFTDI.  You need PIP to install but I think that should already be available in Raspbian.  I’m using Raspbian Jessie (2016-05-27).

$ sudo pip install pylibftdi

The thing to worry about is the port access permission.  You can’t really access the port unless you are a root account or use Sudo to send the command.  This is problematic if you want to be able to just run the interface from any account.  To address this issue, defining a new rule by creating one like this:

 $ sudo nano /etc/udev/rules.d/99-libftdi.rules

Nano is my favorite editor on Raspberry Pi. Add these lines to the rule file then Ctrl+o (letter ‘O’ not zero) to write the file then Ctrl+x to exit.

SUBSYSTEMS=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", GROUP="dialout", MODE="0660"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6014", GROUP="dialout", MODE="0660"

You want to reload the rules so that this new rules take effect.

# Reload rules after edit.
$ udevadm control --reload-rules<\pre>

Now you are ready to try pyLibFTDI. Try listing the devices available by typing in console (not in python):

$ python -m pylibftdi.examples.list_devices

It should list the device(s) assuming you have FTDI device(s) connected to the Raspberry Pi. If you see an empty listing like

::

There’s a permission problem to access the port. Restarting Raspberry Pi seems to help to reload the rules when the reload rules command doesn’t work.

Now we can test pyLibFTDI in python. If you have listed your devices, you can use the device identity to talk to it.  For example, when I ran the list_devices example, I have

FTDI:FT232R USB UART:AK003XYT
FTDI:FT232R USB UART:A603X5C1

These are the 2 FTDI USB devices I have attached to my Raspberry Pi.  I’ll try to talk to the first one.

from pylibftdi import Device
device = Device('AK003XYN')
device.baudrate = 38400
device.open()
device.write('?\r')             #send an identity query command.
                                #This device needs \r to end command.
device.readlines()              #Return data in buffer
device.close()                  #Close the device

These two methods to interface to your FTDI devices should get you started on having an ability to talk to your serial port devices without the need of a Windows based computer.  Enjoy and happy building and coding!

Welcome to my notebook!

I used to have a blog named NetBeansJavaFX2dev on Word Press.  It was intended to be a development journal on using NetBeans with Java FX2, but I haven’t really used it much at all for that.  I then realized that I want to blog about more than just topics related to development in Java FX2 and NetBeans.  Well, I discovered that I could host my own Word Press engine on my own website so why not!   I think I’ll move some of the interesting posts from that other blog here so it’s in one place.  Please feel free to leave comments or say hello.  Cheers.

Old WordPress Site that I used to post to:  https://netbeansjavafx2dev.wordpress.com/