This applet provides a microscopic view of the first law of thermodynamics. Click here for the applet’s url.
Basically, heating is not the only way to change the temperature of a gas. The other way is to do work on it. If the piston charges towards the gas molecules, KE is passed to the gas molecules through the collisions. Higher average KE of gas molecules means higher temperature. On the other hand, if the piston moves away from the gas molecules, the gas molecules actually lose KE through the collisions. The gas cools down since its average KE has been lowered.