Program freezes after a while

Ok, there's something really odd about this problem. It seems it's not related to software at all.

When I'm powering the board from my PC's USB port (through a USPasp programmer), it works normally. However, if I use a 5V 2A AC adapter or a 5V usb charger I've got, the microcontroller eventually freezes after some commands. So it's something related to power supply, but I've never had this sort of problem before.

I also updated the attached sketch on the first post to the latest one.