PIC16F877A don't work properly - led blink and 7 segment display problem
From a quick review of the hardware, I see two problems:


Incorrect crystal load capacitor values:


  I'm using 4MHZ Crystal with 0.1 uF capacitors. Should I change capacitors with 15 pF?




Yes, you must replace those capacitors. 0.1uF is not the correct value and the crystal may not start oscillating at all when using them, or it may only work intermittently, leading to strange behaviour (like you describe).

The required capacitor value also depends on the specific crystal, but your suggested 15pF value is likely to be close enough.
Missing power decoupling capacitors

It's not easy to fully trace the wiring in the photo, but you seem to be supplying power to the PIC via both sets of power pins (pins 11 &amp; 12 and 32 &amp; 31). Good, that is correct. Some people (wrongly) supply power only via one set of power pins, and then sometimes see strange, intermittent problems (especially when switching large output loads).

However you should also add the recommended decoupling capacitors (which typically are 0.1uF) to all Vdd power pins. I don't see any power decoupling capacitors on your breadboard. Therefore add two 0.1uF capacitors - one between pins 11 &amp; 12 and another between pins 32 &amp; 31. Each capacitor should be close to the PIC IC itself. Again, you might see strange, intermittent problems without them.


[Note, I have not gone through your code - I am just highlighting the most visible hardware problems, which may be the cause of your symptoms.]