Why don't you just multiplex them? 40 LEDs would require 5*8 = 13 pins. This would be much easier to implement.