In order to repel a cavalry charge, the infantry should make a formation, such as a square, with backs pointing inwards, and weapons pointing outward.

The horses of the charging cavalry will be very reluctant to approach the wall of weaponry, which will be too dense to jump. The officers will be safely in the middle of the formation.