How can I take a certain amount of items from a chest using a hopper in Minecraft?

I found it always most reliable to count out n of a thing in Minecraft by using a timer that utilizes that thing for own timing. In this case we want to put n items using a hopper, so a timer based on transferring items using hoppers is the optimal solution.

enter image description here

The hopper near the comparator contains as many (arbitrary) items as we want inserted into the minecart. The other hopper of that pair is empty - this, alongside with the two torches, the comparator and a bit of redstone dust, comprises a signal extender that switches the torch on the input block (the one with a button on it; obviously attach whatever timing/activation source you want instead of the button) for duration of moving the items to the other hopper. Meanwhile, there's another hopper next to the same block that locks "return" of the items for the duration of the pulse extension - this one connected to storage and aimed into the minecart. The other torch is connected to a falling edge detector (comprised of 3 repeaters) - after finishing the cycle, the minecart is sent away to distribute the items.

enter image description here enter image description here

Caveats:

  • the signal extender has a "cooldown" of time equal to the duration of the pulse it generates. You must wait at least the same amount of time as it takes to insert the items into the cart, between uses of the system.
  • the hopper aimed into the cart should contain one item, otherwise the first batch will be 1 short.
  • the hopper loading the cart must be fed from a passive container, or from a hopper aimed in a bogus direction (sideways). It can't have items forcefully inserted by another hopper into it while it's locked.
  • the system doesn't have any protections for running out of stock, or activation before the cooldown is elapsed.