Build Go Programs for Raspberry Pi

I tend to do cross compiling with Go >=1.5, so I don’t have to build Go on Raspberry Pi, which is slow.

GOOS=linux GOARCH=arm GOARM=6 go build -a

Please remember to use -a to avoid cached built packages.

Also, please remember to set the correct GOARM version. To get the ARM version, you can run

cat /proc/cpuinfo

On my Raspberry Pi, it outputs

yi@raspberrypi:~ $ cat /proc/cpuinfo
processor	: 0
model name	: ARMv6-compatible processor rev 7 (v6l)
BogoMIPS	: 2.00
Features	: half thumb fastmult vfp edsp java tls 
CPU implementer	: 0x41
CPU architecture: 7
CPU variant	: 0x0
CPU part	: 0xb76
CPU revision	: 7

Hardware	: BCM2708
Revision	: 000e
Serial		: 00000000cd23b897

The line model name : ARMv6-compatible processor rev 7 (v6l) tells that it is ARMv6, so I set GOARM=6.

Writing MPI Programs in Go


// This is a sample MPI program in Go.
//
// To build and run it, we need to install MPI. I downloaded and built
// Open MPI 1.8.8:
//
// wget https://www.open-mpi.org/software/ompi/v1.8/downloads/openmpi-1.8.8.tar.bz2
// tar xjf openmpi-1.8.8.tar.bz2
// cd openmpi-1.8.8
// ./configure –prefix=/home/yi/openmpi
// make -j2 install
//
// This installs Open MPI header files and libraries into /home/yi/openmpi/{include,lib}.
//
// Then I install the Go bindings for MPI: https://github.com/JohannWeging/go-mpi
//
// export CGO_CFLAGS='-I/home/yi/openmpi/include'
// export CGO_LDFLAGS='-L/home/yi/openmpi/lib -lmpi'
// go get github.com/JohannWeging/go-mpi
//
// Now we are ready to build this sample program:
//
// go install
//
// This should generates the binary exectuable `learn-mpi` in $GOPATH/bin. So we can run it
//
// LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/yi/openmpi/lib mpirun -n 4 -hostfile /tmp/hosts $GOPATH/bin/learn-mpi
//
// where /tmp/hosts includes only one line:
//
// localhost
//
// The expected output should be something like:
/*
Hello world from processor centos, rank 3 out of 4 processors
Hello world from processor centos, rank 2 out of 4 processors
Hello world from processor centos, rank 1 out of 4 processors
Hello world from processor centos, rank 0 out of 4 processors
*/
package main
import (
"fmt"
"os"
mpi "github.com/JohannWeging/go-mpi"
)
func main() {
mpi.Init(&os.Args)
worldSize, _ := mpi.Comm_size(mpi.COMM_WORLD)
rank, _ := mpi.Comm_rank(mpi.COMM_WORLD)
procName, _ := mpi.Get_processor_name()
fmt.Printf("Hello world from processor %s, rank %d out of %d processors\n", procName, rank, worldSize)
mpi.Finalize()
}

view raw

learn-mpi.go

hosted with ❤ by GitHub

Raspberry Pi and Arduino

I program and control an Arduino UNO R3 from a Raspberry Pi using C instead of the Processing language.

Development Tools

The official Arduino IDE is Java-based and runs out of my 16GB SD card with Raspbian pre-installed. So I turned to use avr-gcc, which requires me to program using C, instead of the Processing language supported by Arduino IDE. But I like C as it allows me to accurately control my Arduino. To install required development tools:

sudo apt-get install gcc-avr binutils-avr gdb-avr avr-libc avrdude

A Sample Program

An example program named blink.c can be found in this Wikipage. It simply blinks the LED on Arduino board.

I use the Makefile downloaded from here. I only need to edit the first two lines of this Makefile and specify my program name.

Upload Binary

Above Wikipage shows how to use dmesg to identify the Unix device used to connect Arduino. In my case where I use a USB hub, the device is /dev/ttyACM0. The we use the following command line to upload the program:

avrdude -v -v -v -v -carduino -patmega328 -P/dev/ttyACM0 -U flash:w:blink.hex

Live Demo

I recorded this Youtube video to show you how this works. In the video, you can see the LED on my Arduino blinks.

Build WSTP Programs on OSX 10.10 and Mathematica 10

I tried to write a C/C++ program which talks with Mathematica via the WSTP protocol. However, when I build the program using the Makefile provided in directory /Applications/Mathematica.app/SystemFiles/Links/WSTP/DeveloperKit/MacOSX-x86-64/WSTPExamples, clang++ complains during linking that

Undefined symbols for architecture x86_64:
  "std::__basic_file::is_open() const", referenced from:
      WSTP::MLLog::logSelectorToFileWithName(WSTP::mllogselector, char const*) in libWSTPi4.a(mllog.cpp.o)
...

This is because the libWSTPi4.a file bundled with Mathematica 10 was built with libstdc++ on Mac OS X. Therefore, a solution is to add link flag -stdlib=libstdc++ explicitly in the Makefile. For example:

factor : factor.o
        ${CXX} ${EXTRA_CFLAGS} -I${INCDIR} factor.o -L${LIBDIR} -lWSTPi4 -lm -lpthread -stdlib=libstdc++ -lstdc++ -framework Foundation -o $@

An alternative solution is to libraries in /Applications/Mathematica.app/SystemFiles/Links/WSTP/DeveloperKit/MacOSX-x86-64/CompilerAdditions/AlternativeLibraries.

Scala vs Go – Could people help compare/contrast these on relative merits/demerits?

Answer by Nick Snyder:

I have written Go at Google (and in my own time) and Scala at LinkedIn. Both are modern languages with first class concurrency features.

What follows is my subjective comparison of Scala and Go…

Go is an opinionated, minimal language that compiles to machine code.

Scala is a sophisticated, academic, functional, object-oriented, everything-but-the-kitchen-sink, free-for-all language that has a lot of features and runs on the JVM.

Given my experience with both, I would choose Go over Scala every time for one reason: simplicity.

Before I dive in to my answer, I want to make a few general observations:

  • All else equal, less code is easier to understand than more code. All else is rarely equal.
  • Code is read much more often than it is written.
  • Code frequently lives longer than we want it to.
  • The person who tests or maintains a piece of code is frequently not the original author.
  • At scale, the skill level of developers reading/writing/maintaining/testing code is going to be a normal distribution around the mean of "not expert."

Writing code is an act of communication, not just between the author and the compiler (or runtime), but also between the author and a future reader of unknown skill level.

Language complexity

Java 8 language spec is a 780 page PDF (lol, seriously?).
http://docs.oracle.com/javase/sp…

Scala language spec is a 191 page PDF.
http://www.scala-lang.org/docu/f…

The Go language spec is webpage that prints as a 51 page PDF.
http://golang.org/ref/spec

Defining a language is not the same as learning how to use a language, but it is a proxy for how much there is to learn (or how much there is to confuse you when reading someone else's code).

Documentation

I found Go easier to learn, both because it is (objectively) a simpler language and (subjectively) because I think the documentation is better.

Tour:
http://docs.scala-lang.org/tutor…
vs
http://tour.golang.org/#1
http://golang.org/doc/effective_…

FAQ:
http://docs.scala-lang.org/tutor…
vs
http://golang.org/doc/faq

Standard library:
http://www.scala-lang.org/api/cu…
vs
http://golang.org/pkg/

Expressiveness

Given the language specs, it should be no surprise that Scala has more features than Go.

Does that mean Go is any less expressive than Scala?
No, you just might need to write a few extra lines to code to do what you want (but I don't think that is a bad thing).

One of Go's features is that it doesn't have an excess of features, and frankly, I think that feature is undervalued.
http://golang.org/doc/faq#Why_do…

I have yet to encounter a situation in Go where I wished it had a feature that it doesn't.

The Sim City effect

Don't bother Googling this, I just made it up. You know Sim City, right?
SimCity Official Website

If two people start a new city on the same map and play for a few hours, they will produce completely different looking cities.

Why is that?
Because Sim City is a sandbox and there are so many options that it is highly improbable that any two people will make the same series of decisions.

Scala is a sandbox too.
As the other answer alluded to, in addition to the plethora of features that Scala ships with (functional programming features, OO programming features, etc.), Scala exposes capabilities that allow developers to add new features.

This is all well and good until you need to share your sandbox with others and they have no idea what was going on in your head.

Speaking of consistency…

Go is the only language that I know of that has circumvented the whole code style debate by just providing a tool to format your code in the canonical format.
http://golang.org/cmd/gofmt/

Code density

Scala code can be very dense and hard to grok at the early stages of learning.

I would go so far as to say that it is idiomatic in Scala to be as dense as possible, or at least it seems to be that experienced Scala developers have a propensity for terseness.

Example

Consider fetching a user id from a cookie. How much language knowledge do you need to answer the following questions given the implementation?

  • What happens if the cookie is not present?
  • What happens if the cookie value is not a well formatted number?
  • What happens if the cookie value is a negative number?

Scala

1
2
3
4
5
import play.api.mvc.RequestHeader

def getUserId()(implicit request: RequestHeader) = {
  request.cookies.get("uid").map(_.value.toLong).filter(_ > 0)
}

Go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import (
  "fmt"
  "http"
  "strconv"
)

func getUserId(r *http.Request) (int64, error) {
  c, err := r.Cookie("uid")
  if err != nil {
    return 0, err
  }
  i, err := strconv.ParseInt(c.Value, 10, 64)
  if err != nil {
    return 0, err
  }
  if i <= 0 {
    return 0, fmt.Errorf("invalid user id")
  }
 return i, nil
}

In this particular case, the Scala code is clearly shorter and perhaps more eloquent, but the point that I am trying to illustrate in general is that the Go code is explicit and the Scala code requires context to understand.

Be $#%!ing explicit

In my experience, explicit code has a lot of benefits.

  • Explicit code is easier for novices and for non-authors to grok.
  • Explicit code makes the error cases obvious.
  • Explicit code makes the test cases obvious.
  • Explicit code is easier to debug (try setting a breakpoint in the Scala code above).

I have found Go code to be much more explicit than Scala.

Performance

As a developer, the only performance that I care about is my development cycle because I have yet to encounter a runtime that isn't fast enough for what I want to accomplish. Developer time is more valuable than a computer's time anyway.

In my experience, Go is extremely fast to compile, and Scala is slow. YMMV.

To be fair

I learned Go before I learned Scala so I admit that I probably have a bias toward Go. My first reaction to Go was that its syntax was ugly (like C++) but learning Go felt like this:

I learned Scala out of necessity and have gotten used to it; I even like parts of it now, but learning Scala felt like this:

Scala vs Go – Could people help compare/contrast these on relative merits/demerits?