Pinging, knocking and detonation are all terms for a condition known as "pre-ignition". That means some of the gas and air mixture is igniting in the cylinder before it's supposed to. And when that extra flame front crashes into the normal flame front (created by the spark plug), you hear a noise, and that noise is pinging.
There are four major causes of pinging. The first three are related to excessive heat.
The first is severe engine overheating. If the engine is running too hot for any reason, the temperature in the cylinders can simply be too high. In that case, some of the mixture can ignite before the spark plug fires just from the intense heat.
The second major cause of pinging is carbon buildup inside the cylinders and on the pistons. When too much carbon collects, it can reduce the size of the cylinders (increasing the compression and temperature of the cylinder contents) and retain excessive heat itself.
The third cause of pinging is a malfunctioning exhaust gas recirculation (EGR) system. The EGR is supposed to send non-combustible exhaust gas into the cylinders to lower the temperature of the mixture.
How does 800-degree exhaust gas LOWER the temperature in the cylinders? Because it doesn't burn, and it crowds out some of the oxygen that would have burned and made an even hotter flame. And if that EGR is not working properly, the cylinder temperature can be too hot and the engine can ping.
And finally, incorrect ignition timing can cause pinging. The ignition timing determines when the spark plugs fire. And if they're set to fire too early, the stuff will begin to burn too early.