Many bacteria use the flagellum for locomotion and chemotaxis. Its bidirectional rotation is driven by a membrane-embedded motor, which uses energy from the transmembrane ion gradient to generate torque at the interface between stator units and rotor. The structural organization of the stator unit (MotAB), its conformational changes upon ion transport, and how these changes power rotation of the flagellum remain unknown. Here, we present ~3 Å-resolution cryoelectron microscopy reconstructions of the stator unit in different functional states. We show that the stator unit consists of a dimer of MotB surrounded by a pentamer of MotA. Combining structural data with mutagenesis and functional studies, we identify key residues involved in torque generation and present a detailed mechanistic model for motor function and switching of rotational direction.