From The Machinery of Life by David S. Goodsell.

ATP synthase is a molecule-sized generator that converts electrochemical energy into chemical energy. It is composed of two rotary motors connected together by an asymmetric axle. Flow of hydrogen ions through the bottom motor, which is embedded in a membrane, turns the large cylindrical rotor. This is connected to the axle, forcing it to turn inside the second motor at the top. With each turn, the axle distorts the subunits in the upper motor, catalyzing a reaction that makes the unstable phosphate-phosphate bond in ATP (5,000,000 X)

ATP Synthase is incredibly cool because it is probably the closest thing our body has to an honest-to-god recognizable nanomachine as humans would conceive of it. It can pump & rotate in both directions! If there is an electrochemical gradient across the membrane it sits on, it can sap the potential energy of that gradient to synthesize ATP to store energy for later as it lets ions across the membrane. Alternatively, it can consume ATP to pump ions in the opposite direction, creating an electrochemical gradient itself! There are a lot of cool animations you can find online, like this one: https://www.youtube.com/watch?v=kXpzp4RDGJI

How are electrochemical gradients created in the first place? Here’s how plants do it with photosynthesis:

Cyclic Photophosphorylation Plants use the energy of light to make ATP, but they must go through many energy transformations to do it. The process starts with a photosystem protein that captures individual photons of light, and uses the energy of these photons to create high-energy electrons. These electrons then flow through several proteins, hopping through a chain of iron ions and copper ions and slowly losing their energy until they return to the photosystem, ready for another charge from light. As the electrons flow through the cytochrome b₆-f complex, they are used to power the pumping of hydrogen ions across the membrane, creating an electrochemical gradient. This gradient is finally used to power ATP synthase (5,000,000 X)

As always, remember that none of the things we are talking about have any willpower or desire - it’s all just physics and random interactions and energy being moved around. Also remember that none of these systems were designed, but instead came into being through natural selection.