STM32 GPIOs and Template Metaprogramming

December 23, 2009

I posted a new article on my website.

It talks about a performance optimized and high level way of handling STM32 GPIOs using Template Metaprogramming.

CMake part 2: Compiler flags

December 21, 2009

It’s not the first time I talk about CMake in this blog, for the introduction read here. Now it’s time to explore the CMake syntax further. The first CMakeLists.txt looked like this:

cmake_minimum_required(VERSION 2.6)
project(HELLO)

set(HELLO_SRCS main.cpp foo.cpp)
add_executable(hello ${HELLO_SRCS})

As already explained, it successfully creates an executable called “hello” using the main.cpp and foo.cpp source files. But let’s see exactly what CMake does to compile these files. To do so, it is possible to use the commands:

mkdir build && cd build
cmake ../
make VERBOSE=1

The interesting thing here is the VERBOSE=1 option. By default CMake hides the options passed to the compiler, and displays a higher level status indicator with the build completion percentage together with the name of the file currently being built (a much more elegant solution than autoconf). But if the goal is to see the compiler flags used, it is always possible to override this behaviour with the VERBOSE=1 option.

Here is the relevant part of the printout:

[...]
[ 50%] Building CXX object CMakeFiles/hello.dir/main.cpp.o
/usr/bin/c++     -o CMakeFiles/hello.dir/main.cpp.o -c /tmp/cmaketest/main.cpp
[100%] Building CXX object CMakeFiles/hello.dir/foo.cpp.o
/usr/bin/c++     -o CMakeFiles/hello.dir/foo.cpp.o -c /tmp/cmaketest/foo.cpp
Linking CXX executable hello
/usr/bin/c++      CMakeFiles/hello.dir/main.cpp.o CMakeFiles/hello.dir/foo.cpp.o  -o hello
-rdynamic
[...]

Now, if you’ve read my previous blog post on GCC’s compiler flags, you might probably not like what you see, since no optimization flag has been passed to GCC and as a result, your program won’t run as fast as it should.

That’s because no build type has been specified to CMake. The build type is a feature most IDE have, it allows you to compile your program in “debug” mode, for easily single-stepping through it with a debugger, or in “release” mode, with speed optimization enabled.

To fix this you simply need to specify a build type in the CMakeLists.txt file, in this way:

set(CMAKE_BUILD_TYPE Release)

at the end of your CMakeLists.txt file. Of course, change “Release” with “Debug” for debug builds.

With the Release build type, the options passed to the compiler are these:

[...]
[ 50%] Building CXX object CMakeFiles/hello.dir/main.cpp.o
/usr/bin/c++    -O3 -DNDEBUG   -o CMakeFiles/hello.dir/main.cpp.o -c /tmp/cmaketest/main.cpp
[100%] Building CXX object CMakeFiles/hello.dir/foo.cpp.o
/usr/bin/c++    -O3 -DNDEBUG   -o CMakeFiles/hello.dir/foo.cpp.o -c /tmp/cmaketest/foo.cpp
Linking CXX executable hello
/usr/bin/c++   -O3 -DNDEBUG   CMakeFiles/hello.dir/main.cpp.o CMakeFiles/hello.dir/foo.cpp.o
 -o hello -rdynamic
[...]

Much better than before. And if you find uncomfortable to have to edit the CMakeLists.txt file to switch between Release and Debug mode, you can also specify the option in the CMake command line, like this:

mkdir build && cd build
cmake -D CMAKE_BUILD_TYPE=Debug ../
make

Last, if you are a GCC wizard and you want full control of the options passed to the compiler, you can also set them manually. However, keep in mind that a CMakeLists.txt file should ideally work with many compilers. So before forcing compiler options, you need to check that the compiler is really GCC. This is an example that shows how to do it:

cmake_minimum_required(VERSION 2.6)
project(HELLO)

## Target
set(HELLO_SRCS main.cpp foo.cpp)
add_executable(hello ${HELLO_SRCS})

## Compiler flags
if(CMAKE_COMPILER_IS_GNUCXX)
    set(CMAKE_CXX_FLAGS "-O2")        ## Optimize
    set(CMAKE_EXE_LINKER_FLAGS "-s")  ## Strip binary
endif()

Note that you must not specify a build type (Debug or Release) since it apparently conflicts with the manually set compiler flags.

Last note, not necessarily CMake related, if you happen to have a multicore CPU and want to speed up builds, you can use the -jX option of make, where X is the number of cores in your CPU. It tells make to compile X files (lol :D) at the same time. So for a dual core, use:

mkdir build && cd build
cmake ../
make -j2

Openwrt, Fonera and .p12 certificates

November 21, 2009

The most common use of a Fonera is as wireless access point, but it’s not the only possible use. Another possibility is to use the Fonera to connect to an existing wireless network. This can be useful to connect a computer without a wireless card, to set up a “repeater” to extend the range of a wireless network, or to run some application that needs internet connectivity on the Fonera itself (after all, it’s just a Linux based device).

However, when the network you need to connect to requires a WPA enterprise certificate authentication, things can get messy.

This post is just a log of all I had to do to connect my Fonera to one such network, and I think it can be useful to other who have the same need.

First, I’ll describe how to connect to that network using a computer running Linux, using the shell only. It is also possible to use some GUI utility, such as network manager but the shell way is what (in theory) can be usd on the Fonera too, since it has no GUI.
The procedure starts by creating a wpa_supplicant.conf file, with the following content:

ctrl_interface=/var/run/wpa_supplicant
ctrl_interface_group=0
ap_scan=1
network={
ssid="<your network ssid>"
proto=WPA
key_mgmt=WPA-EAP
auth_alg=OPEN
pairwise=TKIP
eap=TLS
anonymous_identity="<your username>"
ca_cert="<your path to the .cer certificate file>"
private_key="<your path to the .p12 ceritficate file>"
private_key_passwd="<your password>"
phase2="auth=MSCHAPV2"
}

And by filling in the required data where there are angle brackets. It is also a good idea to write all the commands to connect in an .sh script file, just like this:

sudo /etc/init.d/network-manager stop
sudo killall wpa_supplicant
sudo ifconfig eth1 down
sudo ifconfig eth1 up
sudo iwconfig eth1 essid <your network ssid>
sudo wpa_supplicant -i eth1 -D wext -c <path to wpa_supplicant.conf>/wpa_supplicant.conf -d &
#wait for connection
sleep 20
sudo dhclient eth1

The script uses a couple of tricks: first it stops network-manager, since it interferes with the manual connection (don’t worry, it will be started again next time you reboot your computer), then the sleep 20 at the end is there to give time to wpa_supplicant to connect to the network before dhclient starts. Of course if you use this you need to replace eth1 with the device name of your wireless card.

This works flawlessly on a Linux computer, but when I tried to connnnect in this way on a Fonera running OpenWrt, it failed. First the Fonera does not have network-manager, so the first line needs to be removed. Then there is no dhclient, but an equivalent program named dhcpcd. But the real problem is wpa_supplicant. When I started it, it failed with the following error:

RSA: Expected zero INTEGER in the beginning of private key; not found
TLSv1: Failed to parse private key
TLS: Failed to load private key
TLS: Failed to set TLS connection parameters
EAP-TLS: Failed to initialize SSL.
TLSv1: Selected cipher suite: 0x0000
TLSv1: Record Layer - New write cipher suite 0x0000
TLSv1: Record Layer - New read cipher suite 0x0000
EAP: Failed to initialize EAP method: vendor 0 method 13 (TLS)

After searching and posting on the OpenWrt forum, the problem was found: to minimize the size of the OpenWrt firmware (some routers only have 2..4MB of FLASH memory…) wpa_supplicant is compiled with an internal (and incomplete) implementation of TLS, which may fail with some certificate types. The solution is to compile a custom wpa_supplicant configured to use OpenSSL as TLS provider.

So I downloaded on my computer running Kubuntu Linux the OpenWrt buildroot with

svn co svn://svn.openwrt.org/openwrt/branches/8.09

configured it with

make meunconfig

in the following way: Network > wpa_supplicant > TLS provider > OpenSSL and disabled timestamp check (since the Fonera does not have a permanent clock and the time is set to 1/1/1970 every time it reboots)

Then I typed “make” and after ~2GB of source files downloaded form the Internet and 1.5 hours of compile time the buildroot compiled a custom firmware  with the required packages.

However when I installed the wpa-supplicant_0.6.3-1.1_mips.ipk file together with the required dependencies libopenssl_0.9.8i-3.2_mips.ipk and zlib_1.2.3-5_mips.ipk  on my OpenWrt it still failed to connect. The problem this time was a lot of ioctl() errors. It looks like the wpa_supplicant package is heavily dependent on the kernel version, so it didn’t work.

The solution was to reflash the Fonera with the firmware that the buildroot compiled together with the wpa_supplicant package. At this point another problem occurred: in the custom firmware the ath0 device, which is the wireless device was not present! At the beginning the problem looked like the lack of the kmod_madwifi package, but the package was present. The solution was to create the device at every reboot with

wlanconfig ath0 create wlandev wifi0

Now that the device was again available, a new problem occurred: wpa_supplicant successfully parsed the certificates, but failed agian to connect, with the following error:

TLS: Certificate verification failed, error 9 (certificate is not yet valid)

The problem was that while the timestamp check was disabled, the date still needed to be within the certificate’s validity range. A quick “date -s” command soved this and finally wpa_supplicant connected to the wireless network.

However, it failed getting an IP address. This because in my custom firmware I forgot to add dhcpcd. Building the dhcpcd package with the buildroot and installing the .ipk package solved this last problem.

In the end the scripts used to connect successfully are these:

wpa_supplicant.conf

ctrl_interface=/var/run/wpa_supplicant
ctrl_interface_group=0
ap_scan=1
network={
ssid="<your network ssid>"
proto=WPA
key_mgmt=WPA-EAP
auth_alg=OPEN
pairwise=TKIP
eap=TLS
anonymous_identity="<your username>"
ca_cert="<your path to the .cer certificate file>"
private_key="your path to the .p12 certificate file>"
private_key_passwd="<your password>"
phase2="auth=MSCHAPV2"
}

connect.sh

## For Fonera + specially compiled OpenWrt
## Developed by TFT

## any date in the certificate validity range is acceptable
date -s 2009.11.20-10:00

killall wpa_supplicant dhcpcd
wlanconfig ath0 destroy

wlanconfig ath0 create wlandev wifi0
ifconfig ath0 down
ifconfig ath0 up
iwconfig ath0 essid <your network ssid>
wpa_supplicant -i ath0 -D madwifi -c /etc/wpa_supplicant.conf -d &
## wait for connection
sleep 20
dhcpcd ath0

Sound controlled lamp

October 20, 2009

That’s a project I’ve done long time ago, but never talked about it in my website.

Here is the link.

OLED displays are getting better every day

October 18, 2009

OLED is a display technology that attracted me from the beginning.

The advantages are:

  • Wider viewing angle (near 180 degrees)
  • Lower response time (order of microseconds, not milliseconds like LCDs)
  • Better contrast compared with LCDs
  • Power consumption depends on the actual number of pixels lit, so it can be lower than LCDs
  • Piexls directly emit light, no need of a backlight
  • Can be made flexible

I used OLED displays in two of my projects, the multi function watch, which uses a 96×64 pixel monochrome yellow OLED, and the Miosix player, with a 128×128 pixel 262K color OLED, and can confirm the advantages of this technology.

However, the reason of this blog post is this video I found on youtube:http://www.youtube.com/watch?v=f8S8tbQMp2k. It looks like another advance in OLED technology. Other than being flexible, it has another advantage: it is much more resistant than an LCD. I hope it will be mass produced soon :)

Using C++ on microcontrollers code size tricks

October 11, 2009

I posted a new article on my website.

It talks about some tecniques to minimize the code size when using GCC and C++ with microcontrollers. It also includes a fully functional template project for an LPC2138 microcontroller.

GCC optimization flags

October 1, 2009

Recently I was talking to a friend of mine who is doing his thesis on parallelizing software on the CELL processor (the one used in the PS3). When benchamrking they found a program that runs nearly four times faster if compiled with the -O3 option. I’ve always specified optimization flags in my projects, and I was aware that they speed up the code a lot, by I was surprised by that figure: four times faster, and without changing the source code!

So, I decided to write a blog post about it. First, let’s start with GCC basics. To compile a C++ file you usually type:

g++ -c file.cpp
g++ -o file file.o

The first line compiles the source code int an object file (file.o), and the second performs the linking step.

To specify an optimization flag, you add -OX to the compiler, were X can be 0,1,2,3 or s; like this:

g++ -O3 -c file.cpp
g++ -o file file.o

Ok, but what optimization flags to choose?

When debugging code, it is necessary to use -O0, which is the equivalent of passing no optimization flags. This is because optimizations confuse debuggers that have difficulties in single stepping your code. (Of course, if you want to debug your code with gdb, you’ll want to enable debugging data, by passing the -g option to the compiler)

When you are releasing your application, it is time to enable optimizations. My advice is to choose the optimization flags in this way:

  • By default, use -O2. It makes your code run fast enough for most applications.
  • If your application need to run very fast, use -O3. This increases the size of the executable file (for example, because it might perform loop unrolling), but it makes it run faster.
  • If you need to minimize the executable size, use -Os plus the -s option that strips from the executable everything except what’s really necessary.

Supertux, cheating at the source code level

September 28, 2009

Who said that there are no games for Linux?

Other than running games for windows through Wine (as well as nearly any other .exe file), there are many games that run natively on Linux.

I don’t play much, but I’ve personally tried Sauerbraten and Supertux, both of which have been suggested to me by admiral0, a member of the POuL.

Supertux is a nice game, but I’ve found it a bit too difficult to play, especially some levels where there are these flying enemies, identified in this picture:

supertux_cheating

So, to finish this almost-impossible level, I decided to cheat :)

And since I’m a programmer, I thought that the easiest way to cheat was to alter the game’s source code :D It did not take much time to download the 0.3.1 beta release (which was the version I was playing) and find what to modify.

The code that makes these enemies attack from the sky is defined in

src/badguy/zeekling.cpp

and is the should_we_dive() member function of the Zeekling class.

Just replace the function’s body with a

return false;

and recompile. The game becomes a little bit easier, and I successfully completed the level :)

FPGA!

September 27, 2009

This is a quick post, more information will follow later. I’m entering the world of reconfigurable hardware :D

Here’s an image of the FPGA board I’ve designed:

fpga

It has an xc3s200 spartan 3 FPGA. It’s not one of the newest nor one of the biggest FPGAs around, but you can synthesize a Microblaze 32bit CPU in it and still have room for other logic.

And there are more good news: Xilinx provides a version of their IDE for Linux, and I even managed to program the FPGA using my JTAG cable and urJTAG.  Here’s an image of urJTAG correctly recognizing the two chips in the JTAG chain:

fpga_screenshot

Until now I’ve only written two simple VHDL programs, one that does an and gate, which is probably the equivalent of the “Hello world” for an FPGA, and one that divides the 50MHz clock on the board by 2^26, and uses the resulting ~1Hz frequency to blink a led. Both work as expected on the FPGA board.

So many interesting things to do, and so little time to do them… it’s 27 September and on 30 September I’ll have to go back to university… This year I had to write my thesis, and that resulted in no spare time during summer… :(

Miosix kernel released

September 23, 2009

After one year of development in the spare time, I released the Miosix kernel under an open source license.

I published the kernel source code, the schematic of the Miosix board, the doxygen documentation, instructions for compiling the kernel, and my thesis.

Read about it here: http://www.webalice.it/fede.tft/miosix/index.html.


Follow

Get every new post delivered to your Inbox.

Join 29 other followers