Toggle KWin Composition Based in Power-Profiles on KDE 4.8

One of the changes in KDE 4.8 was KWin’s new composition / effect toggle handling. As a side effect the power management profiles no longer turn off composition and effects when the AC cord is plugged out.

This behaviour may be fixed in the future, in the meantime, below is a simple workaround:

1. Create a shell script something like this:

if [[ $1 == "on" ]]; then
    if [[ "$(qdbus org.kde.kwin /KWin org.kde.KWin.compositingActive)" = "false" ]] ; then
        qdbus org.kde.kwin /KWin org.kde.KWin.toggleCompositing
elif [[ $1 == "off" ]]; then
    if [[ "$(qdbus org.kde.kwin /KWin org.kde.KWin.compositingActive)" = "true" ]] ; then
        qdbus org.kde.kwin /KWin org.kde.KWin.toggleCompositing
    echo "Usage: $0 [on|off]"

2. Make the script executable (chmod +x) and test it from the command line

3. Go to ‘Energy Saving Settings’ and edit the default ‘On AC Power’ profile. Check ‘Run Script’ and type in:
/full path to your script/script_name on


4. Repeat the same for the “On Battery” profile, but this time pass the argument off

5. Finally test the script by disconnecting the AC power and note that KDE notifies that composition has been suspended. Also running the command:
qdbus org.kde.kwin /KWin org.kde.KWin.compositingActive
Should return ‘false’

Now you can enjoy extended battery life.


Filed under Uncategorized

Using Nvidia Optimus on Linux with Bumblebee

If you have an Optimus enabled laptop with Linux on it there are some good news around.

First, some background. Nvidia released laptops with Optimus based switchable graphics over a year ago but Linux support was missing. This means you must choose in the BIOS between battery guzzling dedicated graphics card or limited on-CPU graphics. On other OS users can choose to run specific application on the dedicated card and keeping it powered down when idle.

For some time now there’s been some unofficial work to get the feature working on Linux (see previous post on the topic). One of this efforts evolved to be the Bumblebee project.

Last week the project released version 0.3. The version features automatic stable and persistent power state. Simply put this means that even if your laptop goes to sleep mode and wakes up, the Nvidia card will stay powered down unless you decide to run an application on it. Aside from automatic power-state setting, the project also allows the user to run OpenGL applications on the Nvidia card with a command ‘optirun’.

Installation process has been greatly simplified, follow the link to instructions for your distribution on the release announcement page.

On the official side Nvidia started looking for ways to provide official support but it seems that this won’t happen in the immediate future.

Meanwhile I highly recommend installing the unofficial support so you can enjoy your switchable graphics card under Linux (for example check out Starcraft II under Wine).

Leave a comment

Filed under Uncategorized

Displaying Floating Point Numbers

What do you do when the system you’re working on doesn’t support printing a floating point variable? Below is a small introduction about floating point numbers and a couple of approaches on float-to-string implementation.

A common task when dealing with sensors is to display the read value as a real number with integer and fraction part. Most systems and languages provides the user with library functions to perform this. For example, in C on a PC one can simply write:
printf("Value: %f", val);
This will print value in the format of AAAA.BBBBB . Printf even allows the user to control the precision (number of digits after the decimal dot) etc.

When working with very small or very large numbers a preferred version would be to use Scientific Notation (i.e: 6.022141e23). In printf notation:
printf("Value: %e", val);

Thing is, that the printf function is very ‘heavy’ and many embedded system implementations choose to supply a limited version without floating point support. So how can we implement these facilities ourselves?

One common solution is to dump the number in its hexadecimal format. For example:
float val = 3.141592;
printf("Value: %08x", *((unsigned int *)&val));

The result would be: 40490fd8
The user can take the value and convert it back to float. The method’s main advantage is that automated systems can always read the value without complicated parsing. The obvious drawback is that it’s really not human-friendly.

The direct approach to display the number in real format would be to write a code like:

void strreverse(char* begin, char* end)
    char tmp;
    while (end > begin)
        tmp=*end, *end--=*begin, *begin++=tmp;

#define ABS(x) ((x) < 0 ? -x : x)
 * Based on one of the versions at:
 * Look there for multiple bases conversion
char *itoa(long value, char* str)
    char *p = str;
    static char digit[] = "0123456789";

    //Add sign if needed
    if(value < 0) *(p++)='-';

    //Work on unsigned
    value = ABS(value);

    // Conversion. Number is reversed.
    do {
        const int tmp = value / 10;
        *(p++) = digit[value - (tmp * 10)];   //like modulu 10, but fast
        value = tmp;
    } while(value);


    strreverse(str,p - 1); //Reverse back number
    return p;

    ftoa - Convert float to ASCII.
    f - Input floating number
    buf - Output string buffer, pre-allocated to sufficient size
    places - places after the decimal point
    Returns pointer to buf.
char *ftoa(float f, char *buf, int places)
    if (signbit(f))
        *(buf++) = '-';

    if (isnan(f)) {
        memcpy(buf, "nan", 4);
        return buf;
    if (isinf(f)) {
        memcpy(buf, "inf", 4);
        return buf;
    long int_part = (long)(f);
    const long prec = lpow(10, places);
    long frac_part = lround((f - int_part) * prec);

    //handle fraction round up to 1.0
    if (ABS(frac_part) == prec) {
        signbit(f) ? int_part-- : int_part++;
        frac_part = 0;

    buf = itoa(ABS(int_part), buf);
    *(buf++) = '.';

    //frac leading zeroes
    if (frac_part) {
        long tmp = ABS(frac_part) * 10;
        while (tmp < prec) {
            *(buf++) = '0';
            tmp *= 10;

    buf = itoa(ABS(frac_part), buf);
    return buf;
static inline long lpow(int base, int exp)
    long result = 1;
    while (exp) {
        if (exp & 1)
            result *= base;
        exp >>= 1;
        base *= base;
    return result;

This implementation is cross-platform and doesn’t rely on the internal format of the floating point number. It’s also limited and not very efficient… the function requires floating point multiplication and comparisons. Why isn’t there a straight forward to print a floating point number?
In almost all modern computer systems single precision floating point number (a.k.a float) is implemented according to the ieee-754 standard. The number’s internal make is as follows:

sign exponent significand (mantissa)
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

The format represents a normalized real number (similar to the scientific notation above). The format also encodes special values like infinity and not-a-number etc.
Still, the format seems very similar to the one we want to print, so why is it so complicated? The answer is its base. The number is coded in binary form. This means the number represented looks like 1.0010101e101. So just like integer form we need to base-convert it to decimal. The manual algorithm can be found here and here. Code example implementing this can be found here or fast low-precision form here.

The base-convert method is faster but also more bug-prone and machine dependent.

Perhaps unsurprisingly the ieee-754 standard also defines decimal-floating point storage, but I must admit that I haven’t seen a modern system with such implementation since binary floating point arithmetic is much simpler for hardware.

In the end I ended up using the simple direct method not requiring in-depth knowledge of the float format. Still there are some uses for the internal structure of floats to approximate inverse square root or exponents.

I’m still missing a fast implementation of function to print a floating point number in scientific notation. Can you recommend one?

For an in-depth look into the floating point implementation and common pitfalls I really recommend reading What Every Computer Scientist Should Know About Floating-Point Arithmetic. The paper covers rounding errors, best practices and removes some of the black magic around the topic.


Filed under code

Debian Squeeze Released

Just in time for the Super Bowl Debian 6.0 (Squeeze) was released earlier today. I’ve been using it on multiple installations fr servers, desktops and laptop and I can report it is rock solid as we’ve come to expect from Debian. Hardware support is very broad (although I don’t know if Intel’s latest Sandy Bridge chipset is supported completely). The software collection is mostly up-to-date, with the exception of desktop environments that are a bit lagged behind (Gnome 2.30, KDE 4.4.5 and Xfce 4.6), all in the name of stability and safe migration from the current stable release.

If you’re planning to install Debian 6.0, please note that this is the first time Debian is releasing their mainline image with no non-free firmware images. This is done to make sure the image is true to the Debian spirit. The step may cause problems to users with hardware that includes non-free firmware (Broadcom NIC’s for example). It is recommended to use the Debian alternative CD or to checkout Debian’s Firmware page.

Debian also launched an updated website with a new branding and good accessibility. The look is refreshing, but a couple of things might be nice to add to the new site. First, it will be useful to link instructions about non-free firmware on the main page and the download links. Second, an official Virtualbox image of Debian would be much appreciated.

While for some people this mark the dist-upgrade season for their servers, I’m planning to move my laptop to the new testing repository and get the all the bleeding-edge latest software releases that were held up due to Squeeze release.

Congratulations to the entire Debian team for this achievement and happy installation for everyone.

Leave a comment

Filed under linux

Nokia and Canonical, the Odd Couple?

What would you say about Canonical and Nokia merger?

On one hand Canonical created Ubuntu, the most popular Linux distribution on desktops, but isn’t getting a significant share in the growing mobile market. Nokia on the other hand, once mobile king, is struggling to hold its place in the new world of smatrphones and tablets. Nokia’s traditional friendly approach to phones now seemed quaint and uninspired on a touch-screen smartphone and Canonical is all but invisible in that market.

Both companies has more in common. Nokia’s experience with open source software hasn’t been completely successful. In the past Nokia purchased and open sourced the Symbian mobile OS, but failed to create community traction. Nokia’s other major open source move, the purchase of the popular Qt framework, has been fruitful , but Nokia isn’t capitalizing on it yet.
Nokia’s latest adventure is a strategic effort to enter the Linux world with Meego, a Linux distribution for the mobile market (actually a joint venture with Intel, AMD, and other non-leaders in the mobile world).
From Canonical’s side things are similar. During the netbook-smartphone-tablet turmoil of the past couple of years, Canonical remained oddly quiet, releasing only the Ubuntu netbook edition. Only recently Canonical started investigating the whole mobile interface with Unity. That marked another step closer to Nokia by choosing Qt as the framework for Unity 2D (which turned to a hit even before official release with upcoming Ubuntu 11.4).
On the practical end of things, Nokia had very little to show in the last CES, especially when it comes to Meego. This may mean Nokia is taking it slow with Linux. Canonical had some mixed experience cooperating with hardware vendors in the past, but it is obvious that both firms has lots to gain from this move. Nokia can become a major player in the Linux world, and Ubuntu can be a valid Apple competitor with the powerful combination of OS and an experienced hardware house.

Leave a comment

Filed under linux, opinion

Powering-Off Discrete Graphics on Switchable Graphics Laptops

Switchable graphics is gaining popularity as a solution to balance performance and power consumption. Linux support for this feature is still very much in development, and until it is the discrete graphics card may take resources even when you don’t use it.

The development of switchable graphics on Linux is being led by Hybrid graphics Linux group. They recently released a driver to turn off the external graphics card. On my system shutting down the card reduced power consumption by 5-10 watts.
Note: This is experimental stuff, your computer may hang or act unexpectedly. Please make sure the discrete graphics card is not being used before proceeding.

Here’s how to test it:
First, install and run poewrtop to get an idea for power consumption (the laptop needs to be disconnected from AC adapter):

sudo apt-get install powertop
sudo powertop

Second, it is recommended to rmmod any kernel modules that may be mapped to the device. For example if you have an Nvidia discrete graphics with the closed source driver running, you should:

sudo rmmod nvidia

Next, download and build the driver:

sudo apt-get install git linux-headers-`uname -r` build-essential
git clone
cd acpi_call
sudo insmod acpi_call.ko
sudo ./

The result of a run should look like (depending on your laptop’s hardware):

Trying \_SB.PCI0.P0P1.VGA._OFF: failed
Trying \_SB.PCI0.P0P2.VGA._OFF: failed
Trying \_SB_.PCI0.OVGA.ATPX: failed
Trying \_SB_.PCI0.OVGA.XTPX: failed
Trying \_SB.PCI0.P0P2.PEGP._OFF: failed
Trying \_SB.PCI0.MXR0.MXM0._OFF: failed
Trying \_SB.PCI0.PEG1.GFX0._OFF: failed
Trying \_SB.PCI0.PEG1.GFX0.DOFF: failed
Trying \_SB.PCI0.XVR0.Z01I.DGOF: failed
Trying \_SB.PCI0.PEGR.GFX0._OFF: failed
Trying \_SB.PCI0.PEG.VID._OFF: works!

Running powertop now should give you about 5-10 watts less.
To test the card is really off you can run the following command:

sudo lspci -vvx

Locate your external graphics card (look for VGA controller with the right make). The card’s PCI configuration space should not be accessible, so it should look something like:

01:00.0 VGA compatible controller: nVidia Corporation GT218 [NVS 3100M] (rev ff) (prog-if ff)
        !!! Unknown header type 7f
00: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff

To re-enable the card, reboot the machine.

Please consider joining the Hybrid graphics Linux mailing list to help the development effort.

1 Comment

Filed under howto, linux

Standalone Coffee Timer – Programming Standalone Arduino by Example

This is a follow-up post on Programming Arduino with Arduino. I’ll show an example of the process based on the Coffee Machine timer. Just to recap the original setup, when connected to Arduino it looked something like:

Coffee machine timer based on Arduino

The Circuit

Here is an updated circuit for the standalone setup:

Coffee timer standalone based on ATMega8

The .sch file can be found here.

You may notice that the new circuit is almost identical to the original. The only significant changes are I/O pin assignments for easier wiring. The IC that drives the circuit is an ATMega8. I chose it since I had a few lying around but it can be replaced with ATMega168 or similar. Note that the footprint here uses Arduino pin annotations. This simplifies identification for software usage. You can get the part from here.
Note: Although not explicitly shown, the 74HC165N shift register should have pin 8 connected to GND and pin 16 to VCC.

The circuit diagram doesn’t include a power supply unit. You can use a basic circuit like this or connect to any regulated 5V power brick (I use a USB wall charger like this or this).

Here’s a picture of the assembled circuit on a breadboard:

Standalone circuit. Things get a little crowded on a single breadboard.

The Code

The CoffeMan.pde sketch was updated to the latest version of Arduino which makes the LiquidCrystal patch redundant. I/O pins are reassigned to match the circuit above.

The Method

First, setup a programming station as described here and place the standalone ATMega chip in the programmer. Alternatively, you can connect your Arduino directly to the standalone by following the ISP pin assignments. If you’re using a new chip, upload the bootloader as explained in step #3. Next, follow steps #4-#7 to set up Arduio IDE to upload sketches via the programmer. Open the CoffeeMan.pde sketch and hit the upload button:

Uploading the sketch with Arduino IDE via a programmer

Once programming completed successfully insert the chip in the target circuit. Connect it to a power source and test it.

Adding Serial Access

Troubleshooting standalone setups can be a pain. Although debugging with LED’s may work, I suggest connecting a serial console via an FTDI breakout or an FTDI cable. The connection is simple enough:

FTDI USB-RS232 connected to Arduino as basic serial console

The FTDI USB-RS232 header is cross connected to the Arduino chip. This means the FTDI TXO (pin 4) is connected to Aruino RX (pin 2). The FTDI RXI (pin 5) is connected to Arduino TX pin (pin 3).
Note: The FTDI Pin 3 can be used as a 5v supply pin. Do not connect it to input voltage.

When connecting the FTDI cable/breakout to a USB port, a new serial port will be registered. You can start it from sketches with standard Serial.begin(…) command and communicate normally as you would with Arduino.

An added bonus is the ability to upload sketches to the chip via the bootloader directly from the Arduino IDE. To accomplish that you’ll need to follow some steps:

  1. Burn bootloader via programmer as shown above
  2. Revert the Arduino IDE preferences file to use bootloader as an upload method
  3. Connect a push button switch between GND and Arduino reset pin (pin #1 on the ATMega)
  4. Open the Arduino IDE and find the FTDI serial port under Tools Serial Port
  5. Load your sketch
  6. Hold the reset button and hit Upload.
  7. Release the reset button
  8. Hope for the best…

The manual reset procedure can be quite annoying. From Sparkfun’s product page on the FTDI breakout, the DTR pin (pin 6) on the FTDI breakout can be used to auto-reset the chip for sketch upload. I didn’t get it quite working, but I’ll post an update if I’m successful.


This post meant to show some handy methods to convert an Arduino based projects to a standalone setup, while maintaining Arduino compatibility for programming and debugging. The method can be used as a step in the life-cycle of a project from concept to production.

Leave a comment

Filed under coffee, production