Keys.RButton | Keys.ShiftKey | Keys.Alt

Let’s assume very simple code for purpose of key detection:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
    Debug.WriteLine(keyData);
}

Whichever key you press you will get short output in Output window. Totally boring.

But interesting thing happens when you press Alt key. Output is (sort of) as expected:

Menu, Alt

However, if you put breakpoint there and hover your mouse over keyData you will see that value is actually Keys.RButton | Keys.ShiftKey | Keys.Alt. Which one is it?

Answer is that it does not really matter. If we check values in Keys enumeration we will find following:

RButton  = 2
ShiftKey = 16
Menu     = 18
Alt      = 262144

We can see or as simple addition and thus Menu + Alt will give you 262162. Same result can also be obtained with RButton + ShiftKey + Alt.

CLR will get just integer with value of 0x40000 (262144 in decimal) from Windows. No matter what you do, it stays in integer domain. When you say Keys.Menu you are just saying 18 in human readable way. So for any text display code actually needs to guess what combination will give that result.

Code that handles string conversion goes from highest element and matches Alt and Menu. Code that handles tooltips matches values from lower end and thus it will find RButton, ShiftKey and Alt. Computer cannot say that one solution is better than other.

Regardless which combination you choose result will be the same.

Something Happened

Illustration

Going around Windows Store I managed to trigger an error “Something happened and your purchase can’t be completed.”

Maybe I am too much of an power user but this message bothers me.

Did problem happen on my computer or remote server? Is author of application at fault? Do I even have connection to server? Am I in wrong region? If I try again will it help? Should I try again now or at some later time? Is error already reported to someone or should I report it?

So many questions and just a short unhelpful message to answer them all…

Next Integer, Please

Generating sequential integers is not hard - simple counter++ is enough. Generating sequential positive integers is as trivial if you can use unsigned type. If you must stay in signed world, wrapping everything in condition will do the trick:

if (counter == Int32.MaxValue) {
    counter = 0;
} else {
    counter++;
}

Things get a bit more interesting if you need to do same in thread-safe manner. Obvious (and simplest) solution would be to put code in lock block:

lock (syncRoot) {
    if (counter == Int32.MaxValue) {
        counter = 0;
    } else {
        counter++;
    }
}

That will make code thread safe but it will also make it a lot slower. Every time you take a full blown lock, you will pay a hefty penalty. This example (on my computer) ran more than 30 times slower compared to first solution.

Only if there was an instruction specialized for integer incrementing…

Well, actually there is one - Interlocked.Increment. Unfortunate feature of this function is that (in case of 32-bit integers) once it goes up to 2147483647 it will return -1 as next value. Simple condition is all it takes to make code work:

Interlocked.Increment(ref counter);
if (counter == int.MinValue) { counter = 0; }

Except that this code does not work.

Any condition that touches our variable without being wrapped in some thread-safe construct will make a mess of things. In this case everything will work properly until variable reaches int.MaxValue (2147483647). Step after that we have a race condition between resetting variable to 0 and incrementing it further. If you have it running in two threads maybe it will even work. If code is running in more than that there is high chance you will see number 0 multiple times. Depending on your luck you might even see negative numbers counting up.

Fortunately code can be fixed:

var currCounter = Interlocked.Increment(ref counter);
if (currCounter < 0) { currCounter = currCounter + Int32.MaxValue + 1; }

We leave counter to increment as it wishes. Once it overflows we let it be - it will loop back eventually. However, there is nothing preventing us from modifying returned value because this value is ours alone and no other thread can touch it. We can simply increase all negative value by 2147483648 and we will get nice sequence of [... 2147483646 2147483647 0 1 ...]. Exactly what we wanted. And variable is held “locked” for only one instruction (Interlocked.Increment) so wait between threads is only as long as it needs to be to insure thread-safe operation.

This code is still more about ten times slower than simple non thread-safe example. But it is three times faster than our first go at locking whole operation. Whether this is even needed highly depends on your code. If you increment number only few times, there is nothing really wrong with locking even whole function. Don’t optimize code before you need to.

Timing routines are available for download. Be sure to measure on release code without debugging (Ctrl+F5). Measuring performance on debugging code is worthless because you might detect bottleneck where there isn’t any.

Distribute Me, Scotty

I’ve been waiting long time for this. Visual Studio finally got official support for distributed source control. I personally find it a bit annoying that they opted for Git instead of Mercurial (which is my favorite) but I still like this move. Distributed source control in any flavor is brilliant.

This will not be available out of box until Visual Studio 2012 update 2. However, there is nothing stopping you from manually installing a preview version.

Based on this I think that we can be fairly certain that days of ugly (or non-existent) Windows interfaces for Git are numbered.

PS: I will stick with Mercurial for now - it has great standalone interface and fairly decent plugin for Visual Studio. But I do see myself in future converting few Mercurial repositories to Git just for fun. :)

Curious UART on 16F1516

Lately I have started using PIC16F1516 as my jelly bean PIC. It is cheap, has lot of memory (whooping 512 bytes) and it is fairly well feature-equipped. Best of all, it is almost completely compatible with my old favorite PIC16F1936.

Yes, PIC16F1936 has EEPROM built-in and both feature list and speed are superior. However, not all projects need all features and speed nor is lack of EEPROM something catastrophic.

As always I started programming by copy/pasting old code. Small adjustments were all that was needed. I copy pasted my UART routines and created simple echoing program on chip. And chip stayed quiet.

After some debugging it was obvious that both my timing routines and UART formulas are correct. And code was same as what I used on PIC16F1936:

void uart_init(int desiredBaudRate) {
    TRISC7 = 1; //RX
    TRISC6 = 0; //TX
    SPBRG  = (unsigned char)(_XTAL_FREQ / desiredBaudRate / 16 - 1);
    BRG16  = 0;    //8-bit
    BRGH   = 1;    //high speed
    SYNC   = 0;    //asynchronous mode
    SPEN   = 1;    //serial port enabled
    TXEN   = 1;
    CREN   = 1;
    asm("CLRWDT");
}

In moment of desperation I turned my attention to datasheet. And there, under Asynchronous Transmission Set-up chapter it said “Set the RXx/DTx and TXx/CKx TRIS controls to ‘1’.”

In all other PICs (I had opportunity to play with) TRIS for TX pin either does not matter or you set it to output. For some reason designers of this PIC decided that TX pin needs to be input in order for USART to work. Quite a trap.

Only change that was required was setting TRISC6 to 1 and my board became alive:

void uart_init(int desiredBaudRate) {
    TRISC7 = 1; //RX
    TRISC6 = 1; //TX
    SPBRG  = (unsigned char)(_XTAL_FREQ / desiredBaudRate / 16 - 1);
    BRG16  = 0;    //8-bit
    BRGH   = 1;    //high speed
    SYNC   = 0;    //asynchronous mode
    SPEN   = 1;    //serial port enabled
    TXEN   = 1;
    CREN   = 1;
    asm("CLRWDT");
}

PS: Do not forget to set ANSELC = 0.